0

After searching on web for validating time as "HH:MM:SS" I found this: Regex pattern for HH:MM:SS time string. but when i put it in my php code i get an error:

preg_match("^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$", "12:33:51", $matches);

this is my error message

Warning: preg_match(): No ending delimiter '^' found in db-dataitem.php on line 128

How could I change the pattern string so it can work for PHP?

Community
  • 1
  • 1
Ehsan Zargar Ershadi
  • 24,115
  • 17
  • 65
  • 95

2 Answers2

6

DATETIME SOLUTION

You can validate all your date/time strings with DateTime::createFromFormat:

Function

function isTimeValid($time, $format = 'H:i:s') {
    $dt = DateTime::createFromFormat($format, $time);
    return $dt && $dt->format($format) == $time;
}

This function can be used for all datetime-combination validation. Examples

Example

foreach (['12:30:54', '13:30:65', '00:00:00', '00:70:00'] as $time) {
    echo "Time '$time' is " . (isTimeValid($time) ? "" : "not ") . "valid.\n";
}

Example output

Time '12:30:54' is valid.
Time '13:30:65' is not valid.
Time '00:00:00' is valid.
Time '00:70:00' is not valid.
Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
4

You should add a delimiter:

preg_match("/^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/", "12:33:51", $matches);

-in PHP pattern is expected to be delimited from modifiers. That delimiter should be non-alphanumeric.

But (as it was done in another good answer) - it's much better to use proper tool for your problem - i.e. validate timestamp via DateTime API.

Alma Do
  • 37,009
  • 9
  • 76
  • 105