I have an app where I am parsing addresses and have been trying to implement the following regex expression to grab a US zip code from an address. once I grab it, I want to remove the zip code from the address string as the zipcode is interfering with grabbing the phone number. However, the following is not grabbing the zipcode.
$string = "John Doe 1234 Main Street Peoria, IL 60601 (555) 555-5555";
function extract_zipcode_from($string){
preg_match_all("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $string, $matches);
return $matches[0];
}
$zip = extract_zipcode_from($string);
$zip = print_r(implode("
", $zip),true);
$string = str_ireplace($zip,"",$string);
Can anyone suggest how to get this to work?
Thanks!
Try this code this will give you phone and zip with out replacing anything .
Assuming that Zip and phone will be always at the end of the string, Anything that comes after zip is a phone number.
$string = "John Doe 1234 Main Street Peoria, IL 60601 (555) 555-5555";
preg_match("/(?P<zip>\d{5})(?P<phone>.*)$/",$string,$match);
echo "Zip : ".$match['zip'];
echo "<br>";
echo "Phone : ".$match['phone'];