Question

I'm trying to use regex to check if a full address string contains a zipcode, can someone help me out?

$address = '10100 Trinity Parkway, 5th Floor Stockton, CA 95219';
if (preg_match('--regex_here--',$ad)) {
    echo 'true';
}
Was it helpful?

Solution

Generally zip codes follow the two letter state code, so something like the following should be fairly reliable:

/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/

Explanation:

\b         # word boundary
[A-Z]{2}   # two letter state code
\s+        # whitespace
\d{5}      # five digit zip
(-\d{4})?  # optional zip extension
\b         # word boundary

You could also change the \b at the end to $ since zip codes are usually (always?) at the end of the address.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top