2010-03-02 87 views
3

我有一个印度公司的数据集,并需要从地址栏提取城市和邮编:PHP匹配字符串

地址字段示例: Gowripuram西,Sengunthapuram后,近LGB,卡鲁尔,泰米尔纳德邦,卡鲁尔 - 639 002,印度

正如你所看到的城市是卡鲁尔(Karur),在 - (连字符)之后跟着拉链。

我需要的PHP代码以匹配[城市] - [拉链]

不知道如何做到这一点我可以找到连字符后的邮编,但不知道如何找到城市,请注意城市可以是2个字。

干杯你time./

Ĵ

+0

这可能是一个愚蠢的问题,但城市名称可以包含逗号或数字吗? – ehdv

回答

0

正则表达式有他们的所有应用程序的地方,但在不同的国家/语言可以为微量的处理时间,增加了不必要的复杂性。

试试这个:

<?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")); 

?> 

未经测试。希望它有帮助〜

0

你可以使用爆炸让所有的字段的数组,你可以在连字符分割。然后你将在一个数组中有2个值。第一个将是你的城市(可以是2个字),第二个将是你的邮编。

$info= explode("-",$adresfieldexample); 
0

我会推荐正则表达式。由于可以预编译表达式,因此如果反复使用它,性能应该很好。

0

下面的正则表达式在$matches[1]中放置“Karur”,在$matches[2]中放置“639 002”。

它也适用于多字城市名称。

$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); 

正则表达式也许可以得到改善,但我相信它符合你的问题规定的要求。

1

试试这个:

<?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 

?> 
0
$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.....