0

I can't get a regex match when there is an hour value given. How can I get a possible hour to match (with or without leading zero)?

$val = '01:04:06'; // doesn't match
$val = '1:04:06'; // doesn't match
$val = '04:06'; // matches
$val = '4:06'; // matches

preg_match("/^([\d]{1,2})\:([\d]{2})$/", $val, $matches);
SomeRandomDude
  • 193
  • 2
  • 9

3 Answers3

1

Just remove the leading ^

You can rewrite your regex as /(\d?\d):(\d?\d)$/ if you want minutes and seconds.

If you want (optionally) the hour, write /((\d?\d):)?(\d?\d):(\d?\d)$/ instead.

Patrick Bard
  • 1,804
  • 18
  • 40
Mid'
  • 81
  • 1
  • 6
0

If you want to match it as a whole, just make a group for the first sequence until :, and added a quantifier, so it could happen 1 or 2 times.

/^(([\d]{1,2})\:){1,2}([\d]{2})$/

Test it here

Patrick Bard
  • 1,804
  • 18
  • 40
0

Here is another one from a similar stackoverflow post but converted for preg_match:

preg_match("/^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/", $val, $matches);
Community
  • 1
  • 1
l33tstealth
  • 821
  • 8
  • 15