views:

53

answers:

3

Hi All,

I'm trying to use preg_match to validate that a time input is in this format - "HH:MM"

+4  A: 
preg_match("/(1[012]|0[0-9]):[0-5][0-9]/", $foo)

for 12-hour or

preg_match("/(2[0-3]|[01][0-9]):[0-5][0-9]/", $foo)

for 24-hour.

Charles
+1 for a specific and concise regex.
Jason McCreary
can you guys please explain how your answer work? I'd like to not only get an answer from you guys, but also try to learn regex.
Catfish
The parentheses before the colon (':') in this instance are so we're able to use | ('or' operator). [0-9] means "a number between 0 and 9". So essentially, the above regex can be explained like this:`(2[0,1,2,3] OR [0,1][0,1,2,3,4,5,6,7,8,9])` `:` `[0,1,2,3,4,5][0,1,2,3,4,5,6,7,8,9])`.
Ashley Williams
this actually doesn't work for anything 12:xx. doesn't work for 12:00 or 12:30 etc.
Catfish
I used the 12 hour version.
Catfish
simple fix. Just changed "/(1[01]|... to "/(1[0-2]|
Catfish
+1  A: 

You can do:

if(preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$input)) {
        // $input is valid HH:MM format.
}
codaddict
This would allow 24:59. That's not a valid time. Furthermore, why aren't you capturing the hour and minute?
Jason McCreary
A: 

You can do this with a preg_match(), but I'd have to be a very specific regular expression. Otherwise 77:99 would be a valid time.

My suggestion would be to explode() the string on the : and then use PHP's date functions to validate the rest and get yourself a timestamp back.

Jason McCreary