4

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,558
  • 4
  • 43
  • 77
Cacoon
  • 2,467
  • 6
  • 28
  • 61
  • 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

4 Answers4

10

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
  • 9,770
  • 3
  • 30
  • 44
2

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
  • 21
  • 2
0
private static final String PATTERN = "([01][01]?[0-9]|2[0-3]):[0-5][0-9]";

The break down: [01][01]?[0-9]->Matches hours that start with 0 or 1 with double digits i.e 00-19 AND 2[0-3]->which matches hours 20-23 THEN you have : which matches : THEN [0-5][0-9] matches 00-59

Brian Brix
  • 449
  • 4
  • 12
  • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Jan 26 '23 at 09:31
-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,558
  • 4
  • 43
  • 77