Skip to content
Advertisement

Regex for 24 hour time

I have found a working expression for accepting only 24 hour time, but my problem is it will accept things before and after such as characters

  • awf23:59fawf
  • 23:59gfes
  • 123:59 Are all accepted, I want to stop allowing this and only accept HH:MM within my statement:

if (preg_match_all(“~((2[0-3]|[01][1-9]|10):([0-5][0-9]))~”, $time)) {

Advertisement

Answer

If you’re wanting to accept only lines that consist solely of the HH:MM pattern, then you can use start of line and end of line anchors, like so:

'/^([01][0-9]|2[0-3]):([0-5][0-9])$/'

If you’re wanting to find words matching HH:MM, then you can use word boundary characters, like so:

'/b([01][0-9]|2[0-3]):([0-5][0-9])b/'

The first would match “04:20”, but not “04:20am” nor “04:20 am”. The second would match “04:20” or the “04:20” portion of “04:20 am”, but not “04:20am”.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement