Regular expression needed for date/time validation
I need a PHP 5 regular expression for the following date/time format:
10 Jul 2010 15:00
(2 digits space 3 characters space 4 digits开发者_JS百科 space 2 digits colon 2 digits)
Character case does not matter, and the only allowed input is a-z, 0-9, space, colon
Thanks in advance.
This matches exactly your specification, which allows anything as a month value.
As you can see, I've grouped each part of the date so you can easily reformat it.
If the string does not match, $m will be 0.
linux-t77m:/home/vinko$ more preg.php
<?php
$d = "10 Jul 2010 15:00";
$m = preg_match("/(\d{2})\s([a-z]{3})\s(\d{4})\s(\d{2}):(\d{2})/i",$d,&$matches);
print_r($matches);
?>
linux-t77m:/home/vinko$ php preg.php
Array
(
[0] => 10 Jul 2010 15:00
[1] => 10
[2] => Jul
[3] => 2010
[4] => 15
[5] => 00
)
To ensure you only have valid months, you can use instead this regexp
$m = preg_match("/(\d{2})\s(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s(\d{4})\s(\d{2}):(\d{2})/i",$d,&$matches);
But... now you only match english months.
This will soon become unwieldy. I strongly suggest you use a datetime handling library and let it handle all these issues.
精彩评论