匹配正则表达式中的固定格式数字和可选字符串

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!";
}