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)) {
2
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”.
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
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
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.
1