php-regexHow to use PHP regex to match a zip code?
PHP regex can be used to match a zip code. The following example code block uses the preg_match()
function to match a zip code with 5 digits:
$zip_code = '12345';
if (preg_match('/^\d{5}$/', $zip_code)) {
echo 'Zip code is valid';
} else {
echo 'Zip code is invalid';
}
The output of the example code is:
Zip code is valid
Code explanation
/^\d{5}$/
: This is the regular expression used to match a zip code with 5 digits. The^
and$
symbols indicate the start and end of the string respectively, and\d
matches any digit. The{5}
indicates that the preceding character (\d
) should be matched 5 times.preg_match()
: This is the PHP function used to match a regular expression against a string. It takes two parameters: the regular expression and the string to match against.
Helpful links
More of Php Regex
- How to match a space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match special characters?
See more codes...