Search code examples
phpregexpreg-match

preg_match time and allow but ignore rest


Im trying to match 24H time in pregmatch and alow spaces and date to be appended on the back.
Im only interested in the time which is the first 5 chars.

so time (first 5 chars) and any thing after that should be allowed, but ignored.

example 23:20 2014-09-29

How far off am I?

     $time = '10:30';
     $pattern = '~^([0-1][0-9]|2[0-3]):([0-5][0-9])$~i';
     if (preg_match($pattern, $time, $m)) {
         print_r(" THATS IS A WRAP");
     } else {
         print_r(" INVALID TIME ");
     }

example 23:20 2014-09-29


Solution

  • Just remove the $ anchor:

    $time = '10:30';
    $pattern = '~^([0-1][0-9]|2[0-3]):([0-5][0-9])~';
    //                                     here __^
    if (preg_match($pattern, $time, $m)) {
         print_r(" THATS IS A WRAP");
    } else {
         print_r(" INVALID TIME ");
    }
    

    Also, the /i modifier is superfluous here because there are not any letters.