开发者

Matching fixed-format numbers and optional string in regex

Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo 开发者_运维知识库"bad format!";
  }

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.


Try this:

/^\d{2}:\d{2}(?:\s?[AP]M)?$/

Here the last part (?:\s?[AP]M)? is an optional, non-capturing group that may start with an optional whitespace character and is then followed by either AM or PM.

For the number ranges replace the first \d{2} by (?:0\d|1[012]) and the second by (?:[0-5]\d|60).


Alternative to using regular expression for matching valid minute and hour you can capture them and then use comparison operators as:

$test = '12:14';
if( preg_match("/^(\d{2}):(\d{2})(?:\s?AM|PM)?$/", $test,$m) &&
    $m[1] >= 0 && $m[1] < 12 &&  
    $m[2] >= 0 && $m[2] < 60) {
        echo "good format";
} else {
        echo "bad format!";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜