Extracting a zip code from an address string

I wrestled a bear once. picture I wrestled a bear once. · Jan 12, 2014 · Viewed 11.2k times · Source

I have some full addresses, for example:

$addr1 = "5285 KEYES DR  KALAMAZOO MI 49004 2613"
$addr2 = "PO BOX 35  COLFAX LA 71417 35"
$addr3 = "64938 MAGNOLIA LN APT B PINEVILLE LA 71360-9781"

I need to get the 5-digit zip code out of the string. How can I do that? Perhaps with RegEx?

An acceptable answer assumes that there could be multiple 5-digit numbers in an address, but the Zip code will always be the last consecutive 5 digit number.

My idea was to use explode then loop through and check each index. Anyone got a better idea?

Any help is greatly appreciated..

Answer

Ilia Rostovtsev picture Ilia Rostovtsev · Jan 12, 2014

Speaking about US zip-codes, which are pre-followed with two letter state code in order to get a zip-code you could use the following regex:

/\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

Online Example

Using it in your PHP:

$addr1 = "5285 KEYES DR  KALAMAZOO MI 49004 2613";
$addr2 = "PO BOX 35  COLFAX LA 71417 35";
$addr3 = "64938 MAGNOLIA LN APT B PINEVILLE LA 71360-9781";

function extract_zipcode($address) {
    $zipcode = preg_match("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $address, $matches);
    return $matches[0];
}

echo extract_zipcode($addr1); // MI 49004
echo extract_zipcode($addr2); // LA 71417
echo extract_zipcode($addr3); // LA 71360-9781

Online Example

EDIT 1:

In order to extend functionality and flexibility, you can specify if you wish to keep state code or not:

function extract_zipcode($address, $remove_statecode = false) {
    $zipcode = preg_match("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $address, $matches);
    return $remove_statecode ? preg_replace("/[^\d\-]/", "", extract_zipcode($matches[0])) : $matches[0];
}
 
    echo extract_zipcode($addr1, 1); // 49004 (without state code)
    echo extract_zipcode($addr2);    // LA 71417 (with state code)
 

Online Example