3v4l.org

run code in 300+ PHP versions simultaneously
<?php function isValidDate(string $date, string $format = 'm/d/Y', string $yearPadding = '19'): bool { $date = preg_replace_callback( '~^(\d+)(\D)(\d+)\2(\d{2}|\d{4})$~', fn($m) => sprintf('%02d/%02d/%d', $m[1], $m[3], str_pad($m[4], 4, $yearPadding, STR_PAD_LEFT)), $date ); // sanitize $d = DateTime::createFromFormat($format, $date); // attempt to parse return $d && $d->format($format) === $date; // check if formatted string is same as sanitized string } $tests = [ '1-1-1992', '1-1-92', '1-01-1992', '1-01-92', '01-1-1992', '01-1-92', '01-01-1992', '01-01/92', '1/1/1992', '1/1/92', '1/01/1992', '1/01/92', '01/1/199', '01/1/92', '01/01/1992', '01/01/92' ]; var_export(array_map('isValidDate', $tests));

preferences:
103 ms | 408 KiB | 5 Q