Richard Richard - 2 months ago 6
PHP Question

Matching specific string format in PHP

I know there are many similar questions on SO about regex and matching, but I just cant get this to work!

I need to check if my string is in the specific format of:

13:30 - 14:00

2 numbers, colon, 2 numbers, space, dash, space, 2 numbers, colon, 2 numbers

This is my best effort so far...

$string = "13:30 - 14:00";
$regex = '^[0-9]{2}:[0-9]{2} - [0-9]{2}:[0-9]{2}$';
if (preg_match($regex, $string)) {
echo "matched pattern";
}


I am a regex noob, and I'm not sure why this isnt working.

Can someone help me to get this regex matching working?

Answer

First: regexp should start/end with / (or #)

Second: - is a special symbol and should be escaped with \

$string = "13:30 - 14:00";
$regex = '/^[0-9]{2}:[0-9]{2} \- [0-9]{2}:[0-9]{2}$/';
if (preg_match($regex, $string)) {
    echo "matched pattern";
}
Comments