regex – What is the MM/DD/YYYY regular expression and how do I use it in php?

regex – What is the MM/DD/YYYY regular expression and how do I use it in php?

The problem is one of delimeters and escaped characters (as others have mentioned). This will work:

$date_regex = /(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)dd/;

$test_date = 03/22/2010;
if(preg_match($date_regex, $test_date)) {
  echo this date is formatted correctly;
} else {
  echo this date is not formatted correctly;
}

Note that I added a forward-slash to the beginning and ending of the expression and escapped (with a back-slash) the forward-slashes in the pattern.

To take it one step further, this pattern wont properly extract the year… just the century. Youd need to change it to /(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]((?:19|20)dd)/ and (as Jan pointed out below) if you want to make sure the whole string matches (instead of some subset) youll want to go with something more like /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]((?:19|20)dd)$/.


As others have mentioned, strtotime() might be a better option if youre just trying to get the date out. It can parse almost any commonly used format and it will give you a unix timestamp. You can use it like this:

$test_date = 03/22/2010;

// get the unix timestamp for the date
$timestamp = strtorime($test_date);

// now you can get the date fields back out with one of the normal date/time functions. example:
$date_array = getdate($timestamp);
echo the month is:  . $date_array[month];    

Its probably better to use strtotime() which will convert nearly any human-readable date format to a unix timestamp. – http://php.net/manual/en/function.strtotime.php

regex – What is the MM/DD/YYYY regular expression and how do I use it in php?

You need correct delimiters around the pattern.

$date_regex = ~(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)dd~;

Leave a Reply

Your email address will not be published.