Validate time format using preg_match

拜拜、爱过 提交于 2020-01-09 11:27:11

问题


I want to validate a time input (like 10:30 am, 02:30 pm) using preg_match()

I use this,

 $pattern   =   "/([1-12]):([0-5])([0-9])( )(am|pm|AM|PM)/";
 if(preg_match($pattern,$time)){
   return true;
 }

But when i give an input like 10:30 pmxxxx it will not validated. I dont know whether the method is correct or not. Help please.


回答1:


The [...] notation in regexes defines character class: something that's applied to the single character. It's alternation that should be used here instead:

0[1-9]|1[0-2]

... so the regex in whole would look like this:

/^(?:0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$/



回答2:


DATETIME SOLUTION

You can validate all your date/time strings with DateTime::createFromFormat:

Function

function isTimeValid($time) {
    return is_object(DateTime::createFromFormat('h:i a', $time));
}

Example

foreach (['12:30 am', '13:30 am', '00:00 pm', '00:00 am', '12:30am', '15:50pm'] as $time) {
    echo "Time '$time' is " . (isTimeValid($time) ? "" : "not ") . "valid.\n";
}

Example output

Time '12:30 am' is valid.
Time '13:30 am' is not valid.
Time '00:00 pm' is valid.
Time '00:00 am' is valid.
Time '12:30am' is valid.
Time '15:50pm' is not valid.



回答3:


REGEX SOLUTION

  • [1-12] will not work, because this is not range definition, but [ and ] means start and end character class definition.
  • use /i pattern modifier at end, so you don't need to write PM, pm, pM, Pm, AM, am, aM, Am combinations.
  • PM and AM fetch can bi simpleffied with [ap]m.
  • if you wish to validate whole string, then the string must be valid from the start to end with ^ and $.
  • I added \h escape sequence (horizontal whitespace char) between time and pm|am, so time like 10:10am can be valid to.

Code:

$time = '10:30 am';
$pattern = '~^(0[0-9]|1[0-2]):([0-5][0-9])\h*([ap]m)$~i';
if (preg_match($pattern, $time, $m)) {
    print_r($m);
    return true;
}

Output

Array
(
    [0] => 10:30 am
    [1] => 10
    [2] => 30
    [3] => am
)


来源:https://stackoverflow.com/questions/12759276/validate-time-format-using-preg-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!