Reputation: 233
Hey could someone help me to test if a string matches 3 double digit figures separated by a colon? For Example:
12:13:14
I understand I should be using preg_match but I can't work out how
Preferably the first number should be between 0 and 23 and the second two numbers should be between 0 and 59 like a time but I can always work that out with if statements.
Thanks
Upvotes: 0
Views: 130
Reputation: 1608
You could use preg_match with number comparissons on $string = '23:24:25';
preg_match('~^(\d{2}):(\d{2}):(\d{2})$~', $string, $matches);
if (count($matches) != 3 || $matches[1] > 23 || $matches[2] > 59 || $matches[3] > 59 ......)
die('The digits are not right');
Or you can even ditch the regular expresions and use explode with numeric comparisons.
$numbers = explode(':', $string);
if (count($numbers) != 3 || $numbers[0] > 23 || $numbers[1] > 59 || $numbers[2] > 59 ......)
die('The digits are not right');
Upvotes: 0
Reputation: 11556
This answer does correct matching across the entire string (other answers will match the regexp within a longer string), without any extra tests required:
if (preg_match('/^((?:[0-1][0-9])|(?:2[0-3])):([0-5][0-9]):([0-5][0-9])$/', $string, $matches))
{
print_r($matches);
}
else
{
echo "Does not match\n";
}
Upvotes: 1
Reputation: 13257
if (preg_match ('/\d\d:\d\d:\d\d/', $input)) {
// matches
} else {
// doesnt match
}
\d
means any digit, so groups of two of those with :
in between.
Upvotes: 0
Reputation: 6052
$regex = "/\d\d\:\d\d\:\d\d/";
$subject = "12:13:14";
preg_match($regex, $subject, $matches);
print_r($matches);
Upvotes: 0