php-regexHow to use regex in PHP to match date in "yyyy-mm-dd" format?
The following regular expression can be used to match a date in the "yyyy-mm-dd" format in PHP:
$regex = '/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/';
This expression will match a string of the form "yyyy-mm-dd" where:
[0-9]{4}
: The year is a 4-digit number(0[1-9]|1[0-2])
: The month is a 2-digit number between 01 and 12(0[1-9]|[1-2][0-9]|3[0-1])
: The day is a 2-digit number between 01 and 31
For example, the following code will return true
if the date is in the correct format:
$date = '2020-04-30';
$regex = '/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/';
if (preg_match($regex, $date)) {
echo 'true';
}
Output example
true
For more information about regular expressions in PHP, see the PHP documentation.
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex with zero or more occurrences?
- How to match a space using PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a year?
- How to use the "s" modifier in PHP regex?
- How to replace a tag using PHP regex?
See more codes...