I want to validate a time input (like 10:30 am, 02:30 pm) using preg_match()
I use this,
$pattern = \"/([1-12]):([0-5])([0-9])( )(a
[1-12] will not work, because this is not range definition, but [ and ] means start and end character class definition./i pattern modifier at end, so you don't need to write PM, pm, pM, Pm, AM, am, aM, Am combinations.[ap]m.^ and $.\h escape sequence (horizontal whitespace char) between time and pm|am, so time like 10:10am can be valid to.$time = '10:30 am';
$pattern = '~^(0[0-9]|1[0-2]):([0-5][0-9])\h*([ap]m)$~i';
if (preg_match($pattern, $time, $m)) {
print_r($m);
return true;
}
Array
(
[0] => 10:30 am
[1] => 10
[2] => 30
[3] => am
)
You can validate all your date/time strings with DateTime::createFromFormat:
function isTimeValid($time) {
return is_object(DateTime::createFromFormat('h:i a', $time));
}
foreach (['12:30 am', '13:30 am', '00:00 pm', '00:00 am', '12:30am', '15:50pm'] as $time) {
echo "Time '$time' is " . (isTimeValid($time) ? "" : "not ") . "valid.\n";
}
Time '12:30 am' is valid.
Time '13:30 am' is not valid.
Time '00:00 pm' is valid.
Time '00:00 am' is valid.
Time '12:30am' is valid.
Time '15:50pm' is not valid.
The [...] notation in regexes defines character class: something that's applied to the single character. It's alternation that should be used here instead:
0[1-9]|1[0-2]
... so the regex in whole would look like this:
/^(?:0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$/