使用preg_match验证时间格式 [英] Validate time format using preg_match

查看:107
本文介绍了使用preg_match验证时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用preg_match()验证时间输入(例如上午10:30,下午02:30)

I want to validate a time input (like 10:30 am, 02:30 pm) using preg_match()

我用这个

 $pattern   =   "/([1-12]):([0-5])([0-9])( )(am|pm|AM|PM)/";
 if(preg_match($pattern,$time)){
   return true;
 }

但是当我输入类似10:30 pmxxxx的输入时,它将不会被验证. 我不知道该方法是否正确.请帮助.

But when i give an input like 10:30 pmxxxx it will not validated. I dont know whether the method is correct or not. Help please.

推荐答案

正则表达式中的[...]表示法定义了 character 类:应用于单个字符的类.应该在这里改用替代方法:

The [...] notation in regexes defines character class: something that's applied to the single character. It's alternation that should be used here instead:

0[1-9]|1[0-2]

...所以整个正则表达式看起来像这样:

... so the regex in whole would look like this:

/^(?:0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$/

这篇关于使用preg_match验证时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆