PHP Code:
<?php
$time = '21:50PM';
// Returns 1 if valid, 0 if not valid, false if $time hasn't been set
function check12Hour($time = null) {
if (!$time)
return false;
return preg_match('/^(0[1-9]|1[0-2]):([0-5][0-9])(AM|PM)$/', $time);
}
echo check12Hour($time);
?>
I'm no expert with regex, but I am slowly getting better.
I think the trick is to build them one step at a time, testing it out as you go.
For example:
Start out with an idea of what valid is. In this case 09:00AM is valid.
Set up the format: '//'
Then go step by step:
Code:
'//'
'/^09:00AM$/' // ^ means starts with, $ means ends with
// The first "group" is the first two digits of the time
// Parenthesis around a group
// Now think about all possible values for the first two digits
// You can have a 0 followed by a 1-9 OR a 1 followed by a 0-2
// 0 followed by a 1-9 is written 0[1-9]
// Use | ( the pipe char ) for OR
'/^(0[1-9]|1[0-2]):00AM$/'
// Next you want a single colon, so type that.
// Then move on to the next group
// Parenthesis and follow the same idea as before
'/^(0[1-9]|1[0-2]):([0-5][0-9])AM$/'
// Then the AM OR PM gets some parenthesis
'/^(0[1-9]|1[0-2]):([0-5][0-9])(AM|PM)$/'
// And that's it
'/
Bookmarks