I want a regular expression to use in preg_match
to check whether or not a date is in the pattern DD/MM/YYYY
. I tried the code below, but it didn't work:
preg_match("#^[1-31]*1[1-12]*1[1950-2013]?#", $date);
I want a regular expression to use in preg_match
to check whether or not a date is in the pattern DD/MM/YYYY
. I tried the code below, but it didn't work:
preg_match("#^[1-31]*1[1-12]*1[1950-2013]?#", $date);
Your regex translates to:
- From the start of the string,
- Look for any number of characters in the range 1 through 3, or the character 1
- Look for a literal 1
- Look for any number of characters in the range 1 through 1, or the character 2
- Look for a literal 1
- Look for either one or zero of the characters 1, 9, 5, 0 through 2, 0, 1 or 3
It very obviously doesn't make sense.
You can't validate a date in regex, since dates are not regular. You have different numbers of days in each month, leap years, and a bunch of other stuff. You would be better off separating your date into pieces (use explode
) and check it with checkdate()
Your regex is so wrong that I don't even know where to start explaining.
But the simplest answer is: don't use regex for this. PHP has perfectly good date handling routines already. For example, DateTime::createFromFormat()
...
$date = DateTime::createFromFormat('Y/m/d', $dateString);
echo $date->format('j-M-Y'); //outputs something like '15-Feb-2009'
See http://www.php.net/manual/en/datetime.createfromformat.php
You could use preg_match("/^\d{1,2}\/\d{1,2}\/\d{4}/",$date);
however a regex isn't well-suited for this task because there you will still need to perform additional validation ("9999" is a valid year, for example). I think instead you may want to take a look at date_parse_from_format()
, like:
date_parse_from_format('d/M/Y', $date);
See Convert String To date in PHP for more information.