2

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)) {

Akshay
  • 3,164
  • 3
  • 35
  • 72
Cacoon
  • 2,195
  • 5
  • 24
  • 56
  • http://www.regular-expressions.info/anchors.html – user3942918 Mar 27 '17 at 05:52
  • 1
    Possible duplicate of [Regular expression for matching HH:MM time format](http://stackoverflow.com/questions/7536755/regular-expression-for-matching-hhmm-time-format) – Niklesh Raut Mar 27 '17 at 05:53
  • @Niklesh wasnt a duplicate, but that link helped me out. I just need '^' at the start and '$' at the end – Cacoon Mar 27 '17 at 06:07

3 Answers3

8

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".

phatfingers
  • 8,760
  • 1
  • 27
  • 42
0

I didn't understand it until I broke it apart like this

# ^   look at start of line
# ( to start encapsulate to look at hours
# 0? to indicate hours could have a leading 0 and a number
# [] to indicate range of second digit of that number between 0 and 9
# | 
# 1 to indicate if first digit is 1
# [] to indicate range of second digit ofthat number between 0 and 9
# |
# 2 to indicate if first digit is 2
# [] to indicate range of second digit of that number between 0 and 9
# ) to close encapsulate
# :   to indicate minutes
#  [] to indicate 1st digit can be from 0 to 5
#  [] to indicate 2nd digit can be from 0 to 9
palomar
  • 1
  • 1
-1

Haven't checked you whole regex.

It seems ~ has problem, you should use, ^ for start and $ for end.

if (preg_match_all("^((2[0-3]|[01][1-9]|10):([0-5][0-9]))$", $time)) { this should work.

Akshay
  • 3,164
  • 3
  • 35
  • 72