1

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';
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Joe
  • 1,762
  • 9
  • 43
  • 60
  • is the zip code going to be a separate string from the address? – Ryan Jun 19 '12 at 18:11
  • possible duplicate of [What is the ultimate postal code and zip regex?](http://stackoverflow.com/questions/578406/what-is-the-ultimate-postal-code-and-zip-regex) – hakre Jun 19 '12 at 18:19

1 Answers1

7

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • I didn't think ZIP codes included the state code. I thought it was just the 5 digits or ZIP+4. – sachleen Jun 19 '12 at 18:41
  • 1
    @sachleen - The ZIP code does not include the state code, but if you just checked for five digits you might catch street numbers or apartment numbers. Adding the state code check is just some extra verification that the number is actually a ZIP code. – Andrew Clark Jun 19 '12 at 18:51
  • Makes sense. I misunderstood your response the first time. ZIP code just follows the state code, not includes it. – sachleen Jun 19 '12 at 18:53