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);
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.
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})$/
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);