1

Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

2 Answers 2

3

Try this:

/^\d{2}:\d{2}(?:\s?[AP]M)?$/

Here the last part (?:\s?[AP]M)? is an optional, non-capturing group that may start with an optional whitespace character and is then followed by either AM or PM.

For the number ranges replace the first \d{2} by (?:0\d|1[012]) and the second by (?:[0-5]\d|60).

Sign up to request clarification or add additional context in comments.

4 Comments

@Ben: You’re welcome! By the way, minutes would only go from 0–59 as 60 already is the next hour. And as for the hours, 12=0 in the next 12-hour period.
Can I trouble you for a little more info? Im trying to support 24 hour time format so the first two digits i.e. can be <=24, however I do not understand the syntax fully - (?:0\d|1[012]). Can you advise on how this breaks down? Many thanks, Ben.
@Ben: (?:0\d|1[012]) is a non-capturing group (?:…) containing an alternation of either a 0 followed by a digit, or a 1 followed by one of 0, 1, and 2. So for 24 hours period you would use (?:[01]\d|2[0-4]) (or 2[0-3] for 20 to 23).
Got it! Thank you, the explanation has been very helpful indeed. Regards, Ben.
0

Alternative to using regular expression for matching valid minute and hour you can capture them and then use comparison operators as:

$test = '12:14';
if( preg_match("/^(\d{2}):(\d{2})(?:\s?AM|PM)?$/", $test,$m) &&
    $m[1] >= 0 && $m[1] < 12 &&  
    $m[2] >= 0 && $m[2] < 60) {
        echo "good format";
} else {
        echo "bad format!";
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.