0

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

2
  • Here's a great reference site for learning regex: regular-expressions.info May 25, 2012 at 13:54
  • Do the minute and second fields have to be two digits (e.g., :04:09) or no leading zeros (e.g., :4:9)?
    – BryanH
    May 25, 2012 at 13:58

4 Answers 4

1

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";
}
0

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');
3
  • The first of these answers will not accept the strings where the second digit of the hours is greater than 3, or second digit of minutes or seconds is 6,7 or 8 (e.g. "14:00:00", "12:07:00", "12:00:07"). The second answer will accept a correct value srrounded by junk (e.g. "012:34:56789"). The third answer will accept non-numeric values (e.g. "a:b:c"), missing parts (e.g. "12:34") or even an empty string ("").
    – qbert220
    May 28, 2012 at 15:22
  • before running the if, check if sizeof($numbers) returns >= 2
    – Cole Tobin
    May 28, 2012 at 18:04
  • You are right! I corrected the answer and deleted the first part. I left the other ones because they use numeric comparisons to validate that the string has the desired format.
    – mpratt
    May 28, 2012 at 18:06
0
$regex = "/\d\d\:\d\d\:\d\d/";

$subject = "12:13:14";

preg_match($regex, $subject, $matches);

print_r($matches);
0
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.