Regex Failing to Validate ISO Date Format
Question:
Why isn't the following regular expression, intended to match ISO-style dates, working as expected?
if(preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([1-2]{1})([0-9]{1}):([0-5]{1})([0-9]{1}):([0-5]{1})([0-9]{1})$/', $date) >= 1) // ...
Answer:
While the regular expression itself is valid, the issue here lies in the use of forward slashes "/" as delimiters. PHP requires double quotes " or single quotes ' as delimiters for regular expressions, not forward slashes.
To correct this issue, replace the forward slashes with double quotes:
if(preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([1-2]{1})([0-9]{1}):([0-5]{1})([0-9]{1}):([0-5]{1})([0-9]{1})$/', $date) >= 1) // ...
Now the regular expression will correctly match ISO-style dates.
Advantages of Using DateTime Class:
Although the corrected regular expression will validate ISO dates, it's worth considering the DateTime class for date and time validation and manipulation. The DateTime class is more comprehensive and can handle a wide range of date and time formats.
The following example shows how to use the DateTime class to validate an ISO-style date:
function validateDate($date, $format = 'Y-m-d H:i:s') { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; }
The above is the detailed content of Why is my PHP regex failing to validate an ISO date format?. For more information, please follow other related articles on the PHP Chinese website!