开发者

PHP: Time validation RegEx?

I am using following regex to validate date in format dd/mm/yyyy in php:

preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $e_startdate, $matches)

But what will be the regex to validate time in the format 10:20 PM or AM. I want a regex which will validate following format for me.

<number><number><colon><number><number><space><AM or PM>
开发者_Python百科

Thanks


You can use the regex:

(0[0-9]|1[0-2]):[0-5][0-9] [AP]M


The following should validate the format you requested:

preg_match("/(\d{2}):(\d{2}) (AM|PM)/", $e_startdate, $matches);

Note that this is not necessarily a valid time. You could enter stuff like 32:62 AM. You need something like this for time validation:

preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", $e_startdate, $matches);

Mind to match the whole thing case-insensitive (like i did in the second example). Otherwise lowercase am, pm, etc. are not going to work.


Regular Expression:

(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])

Validates time in MySQL time format. 24 hour time colon separated hours:minutes:seconds hh:mm:ss

Matches: 09:30:00 | 17:45:20 | 23:59:59

Non-Matches: 24:00:00


/\d{2}:\d{2} (AM|PM)/


I started with elusive's answer, but needed a bit more flexibility. This one makes the minutes optional, as well as the space before AM/PM

/(0?\d|1[0-2])(:(0\d|[0-5]\d))?[ ]?(A|P)M/i
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜