Regular Expression in PHP

hrolsons
hrolsons used Ask the Experts™
on
If I have a string:

$mystring="12/11/1970";

or:

$mystring="Unknown";

How can I evaluate that sting to see if it is in the format mm/dd/yyyy?

Thank You.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

if (preg_match("/\d\d\/\d\d\/\d\d\d\d", $mystring))
{
    echo "A match was found.";
} else
{
    echo "A match was not found.";
}

Open in new window

Forgot the final slash.
if (preg_match("/\d\d\/\d\d\/\d\d\d\d/", $mystring))
{
    echo "A match was found.";
} else
{
    echo "A match was not found.";
}

Open in new window

Commented:
This one also looks for dates that are in valid ranges:
<?php
  
  $string = '12/02/2009';
  
  $regex = '#^(0[1-9]|1[1-2])/(0[1-9]|[1-2][0-9]|3[0-1])/(19|20)[0-9]{2}$#';
  
  if (preg_match($regex, $string)) {
    echo 'valid date';
  } else {
    echo 'invalid date';
  }
  
?>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial