Marko Basta
Marko Basta

Reputation: 47

RegEx for matching time in PHP

I want to check time input format with regular expression.

I did this to check this format "H:m" (24 hour format):

$date = '23:59';

if(!preg_match('/^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$/', $date)) {
    form_set_error('Error in time format');
}

Now I need also to check this format:

"H:m - H:m"

when

$date = '09:00 - 10:00';

How do I solve this problem?

Upvotes: 1

Views: 89

Answers (2)

Emma
Emma

Reputation: 27723

You could simply remove the start and end chars and check if it matches any time, maybe similar to:

$re = '/(2[0-3]|[01]?[0-9]):([0-5]?[0-9])/m';
$date = '09:00 - 10:00';

preg_match_all($re, $date, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $value) {
    echo $value[0] . " is a match \n";
}

Output

09:00 is a match 
10:00 is a match

Combining RegEx

If you wish to combine two regular expressions, you can simply use a logical OR and place your expressions in two capturing groups:

(expression 1)|(expression 2) 

Upvotes: 1

dvo
dvo

Reputation: 2153

(2[0-3]|[01]?[0-9]):([0-5]?[0-9])(\s*-\s*(2[0-3]|[01]?[0-9]):([0-5]?[0-9]))?
  • (2[0-3]|[01]?[0-9]):([0-5]?[0-9]) - your regex from question
  • (\s*-\s*(2[0-3]|[01]?[0-9]):([0-5]?[0-9]))? - optional "- 00:00"
    • \s*-\s* - optional space, dash, optional space (remove * to make not optional)
    • (2[0-3]|[01]?[0-9]):([0-5]?[0-9]) - your regex again
    • ? - makes second part optional. Means 0 or 1 of preceding group. (remove this ? to make it not optional)

Upvotes: 1

Related Questions