Will
Will

Reputation: 1933

PHP get if string is a time in the format 00:00

I have a string which may be a time or may be something else entirely. I want to find out if the string is in the format 00:00. I don't need to check whether the string is a valid time (ie not something like 25:98), just whether the string is in that format.

Upvotes: 0

Views: 3067

Answers (4)

Emanuele Minotto
Emanuele Minotto

Reputation: 415

if (preg_match('/^[0-9]{2,2}:[0-9]{2,2}$/', $string))
{
    // ...
}

Upvotes: 0

stema
stema

Reputation: 92976

Try this

/\b\d{2}:\d{2}\b/

\b is a word boundary to ensure that there is nothing else before or ahead

\d is a digit, \d{2} means two digits.

Upvotes: 0

Shef
Shef

Reputation: 45589

The regex would be /^\d{2}:\d{2}$/. Which matches a string if and only if it contains 2 digits before the colon and two digits after the colon.

Here is a PHP if/else condition with the above regex:

if (preg_match('/^\d{2}:\d{2}$/', $time)) {
    // it is in the time format
} else {
    // it is not in the time format
}

Upvotes: 5

Mchl
Mchl

Reputation: 62367

And regex for that would be ^[0-9]{2}:[0-9]{2}$

Upvotes: 2

Related Questions