views:

128

answers:

2

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 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.

+1  A: 

sounds like http://stackoverflow.com/questions/2811535/php-datetime-regex

SteveCav
Not quite. I only need to check that the field is in that particular format. If it is then I convert it to a MYSQL friendly format. If not then then an error is displayed to the user.
GSTAR
+3  A: 

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.

Vinko Vrsalovic
Good stuff mate. That's actually raised a very good point - how can I also ensure the month is a valid 3 character month name?
GSTAR
@GSTAR: If a string matches the regular expression, then check the month against the twelve possibilities manually.
David Zaslavsky
Cheers again. I would use that datetime class but it tells me it's only enabled in 5.3, which my host does not currently provide. I think the above solution you've provided will work fine for me, I don't think I'd need anything other than English month names anyway :)
GSTAR
Hi Vinko, how can I ensure that the whole pattern is matched and that no more text can be added after the time (15:00)? With the above expression I am able to add text in after the time and it does not give an error.
GSTAR
@GSTAR: /(\d{2})\s(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s(\d{4})\s(\d{2}):(\d{2})$/i
Vinko Vrsalovic