tags:

views:

158

answers:

6

Hi,

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

A: 

You could use explode to make an array of all the fields, you can split them on the hyphen. You will have 2 values in one array then. The first will be your city (can be 2 words) the second will be your zip.

$info= explode("-",$adresfieldexample);
Younes
A: 

I would recommend regular expressions. Performance should be good if you're using it over and over since you can precompile the expression.

marr75
A: 

The following regex places "Karur" in $matches[1] and "639 002" in $matches[2].

It also works for multi-word city names.

$str = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

preg_match( '/.+, (.+) - ([0-9]+ [0-9]+),/', $str, $matches);

print_r($matches);

Regex can probably be improved, but I believe it meets the requirements specified in your question.

Mike
+1  A: 

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

?>
codaddict
A: 

Regex have their place in all applications, but in different countries/languages you can add unnecessary complexity for micro amounts of processing time.

Try this:

<?php

$str  = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";
$res  = substr($str,strpos($str, "," ,3), strpos($str,"\r"));
//this results in " Karur - 639 002, India";

$ruf  = explode($res,"-");
//this results in 
//$ruf[0]="Karur " $ruf[1]="639 002, India";

$city    = $ruf[0];
$zip     = substr($ruf[1],0,strpos($ruf[1], ",");
$country = substr($ruf[1],strpos($ruf[1],","),strpos($ruf[1],"\r"));

?>

Not tested. Hope it helps~

Peter G Mac.
A: 
    $info="Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

$info1=explode("-",$info);

$Hi=explode(",","$info1[1]");

echo $Hi[0];

hopes this will help u.....
rag