I have an Indian company data set and need to extract the City and Zip from the address field:
Address Field Example: Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India
As you can see the City is Karur and the zip is followed after the - (hyphen).
I need the PHP code to match [city] - [zip]
Not sure how to do this I can find the Zip after the Hypen but not sure how to find the City, please note the City can be 2 words.
Cheers for your time./
J
Try this:
<?php
$address = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";
// removes spaces between digits.
$address = preg_replace('{(\d)\s+(\d)}','\1\2',$address);
// removes spaces surrounding comma.
$address = preg_replace('{\s*,\s*}',',',$address);
var_dump($address);
// zip is 6 digit number and city is the word(s) appearing betwwen zip and previous comma.
if(preg_match('@.*,(.*?)(\d{6})@',$address,$matches)) {
$city = trim($matches[1]);
$zip = trim($matches[2]);
}
$city = preg_replace('{\W+$}','',$city);
var_dump($city); // prints Karur
var_dump($zip); // prints 639002
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With