是否有最佳实践或通用算法来实现位置位置(仅限美国)的自然搜索字符串转换为单独的组件?
例如:
City Name, ST 00000
TO
city => City Name
state => ST
zipcode => 00000
这是一个表单所以我不需要处理任何可能的排列 - 我可以将格式限制为:city, st 00000
但我需要能够处理格式中任何段的遗漏,以便它们在某种程度上是可选的...支持组合的一些示例(不区分大小写):
00000 // zipcode
0000-00000 //zipcode
city, st / city and state - comma separated
city st // city and state - space separated
city, st 00000 // city state zip
st 00000 // state and zip - though i only really need the zip
city 00000 // city and zip - though i only really need the zip
我还可以使用静态的State缩写集,以便在需要时可以匹配这些缩写来验证状态段。
答案 0 :(得分:1)
<?php
function uslocation($string)
{
// Fill it with states
$states = array('D.C.', 'D.C', 'DC', 'TX', 'CA', 'ST');
// Extract state
$state = '';
foreach($states as $st)
{
$statepos = strpos(' '.$string, $st);
if($statepos > 0)
{
$state = substr($string, $statepos-1, strlen($st));
$string = substr_replace($string, '', $statepos-1, strlen($st));
}
}
if(preg_match('/([\d\-]+)/', $string, $zipcode))
{
$zipcode = $zipcode[1];
$string = str_replace($zipcode, '', $string);
}
else
{
$zipcode = '';
}
return array(
'city' => trim(str_replace(',', '', $string)),
'state' => $state,
'zipcode' => $zipcode,
);
}
// Some tests
$check = array(
'Washington D.C.',
'City Name TX',
'City Name, TX',
'City Name, ST, 0000',
'NY 7445',
'TX 23423',
);
echo '<pre>';
foreach($check as $chk)
{
echo $chk . ": \n";
print_r(uslocation($chk));
echo "\n";
}
echo '</pre>';
?>
答案 1 :(得分:0)
在我研究的过程中,我发现在我等待时使用的另一个SO question引用了一些其他代码...我在这里修改了代码以支持获取邮政编码以及城市状态:{{3 }}
其他人也可能会发现http://www.eotz.com/2008/07/parsing-location-string-php有用。
@delphist:谢谢。一旦我有时间比较准确性和性能,我可以切换到你的代码,如果它更好 - 它当然更简单/更短!如果我这样做,请将其标记为正式答案。