Why Isn't My ISO Date Matching Pattern?
The given regular expression:
/^([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})$/
is designed to match ISO-style dates in the format "YYYY-MM-DD HH:MM:SS." However, it returns false despite meeting the criteria. The issue lies in the slashes (/) enclosing the expression.
PHP Regular Expression Delimiters
In PHP, regular expressions must be enclosed within delimiters, typically slashes (/), but double quotes (") can also be used. The / delimiter is used to define the beginning and end of a regular expression and to prevent conflicts with other special characters within the expression.
Resolving the Issue
To resolve the issue, ensure the following:
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)
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)
Alternative Option Using DateTime Class
Instead of using a regular expression, consider using the PHP DateTime class, which provides more robust and reliable date validation and manipulation capabilities:
function validateDate($date, $format = 'Y-m-d H:i:s') { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; }
This function returns true for valid dates and false for invalid ones. It can be used to validate dates in various formats, including ISO.
The above is the detailed content of Why Isn't My PHP ISO Date Regular Expression Matching?. For more information, please follow other related articles on the PHP Chinese website!