我找到了一个只接受24小时时间的工作表达式,但我的问题是它会接受字符之前和之后的内容
if(preg_match_all("〜((2 [0-3] | [01] [1-9] | 10):( [0-5] [0-9]))〜&#34 ;,$ time)){
答案 0 :(得分:2)
如果您只想接受仅由HH:MM模式组成的行,那么您可以使用行首和行尾锚点,如下所示:
'/^([01][0-9]|2[0-3]):([0-5][0-9])$/'
如果您想找到匹配HH:MM的单词,那么您可以使用单词边界字符,如下所示:
'/\b([01][0-9]|2[0-3]):([0-5][0-9])\b/'
第一个匹配“04:20”,但不是“04:20 am”和“04:20 am”。第二个匹配“04:20”或“04:20”部分“04:20 am”,但不是“04:20 am”。
答案 1 :(得分:0)
直到我把它拆成这样我才明白
# ^ 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
答案 2 :(得分:-1)
没有检查你整个正则表达式。
似乎~
有问题,
您应该使用^
作为开始,$
作为结束。
if (preg_match_all("^((2[0-3]|[01][1-9]|10):([0-5][0-9]))$", $time)) {
这应该有用。