I just can’t leave well enough alone. This third iteration of the PHP isDate function is a little more concise, and makes changing acceptable formats a little easier. The function signature stays the same, accepting a date, and the expected format of the date, using PHP date expressions.



1. accepts a date, and a date format (not a regular expression)

function isDate($d, $f='m-H:%M'){

$dateFmtRE = array(
'/\//' => '\/',
'/%d|%e/' => '(0?[1-9]|[12][0-9]|3[01])',
'/%m/' => '(0?[1-9]|1[012])',
'/%g|%G|%y|%Y/' => '(19\d\d|20\d\d)',
'/%H|%I|%l/' => '([0-1]?\d|2[0-3])',
'/%M/' => '([0-5]\d)');
if (empty($d)) return true;

#convert Unix timestamp to a std format (must not include regular expressions)
if (preg_match('!\d{5,}!', $d))
$d = strftime($f, $d);

return (
#does %d match the regular expression version of $f? if it does m/d/y are in $x
preg_match('!^' .preg_replace(array_keys($dateFmtRE), array_values($dateFmtRE),$f) .'$!', $d, $x)
&& (checkdate($x[2], $x[1], $x[3]) || checkdate($x[1], $x[2], $x[3]) || checkdate($x[3], $x[1], $x[2]))
?true :false);

}