Extracting a zip code from an address string
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