我有一个包含地址的字符串,我需要知道该地址使用的是哪种街道类型。下面是一个示例:
$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");
//find and save the street type in a variable
//Response
echo "We have found ".$streetType." in the string";
此外,地址是由用户提交的,格式永远不会相同,这使事情复杂化。到目前为止,我已经看到了这样的格式:
100 ROAD OVERFLOW
100,road Overflow
100, Overflow road
解决此问题的最佳方法是什么?
从您的字符串和您要查找的单词集开始:
$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");
首先将字符串转换为大写并使用 preg_split
拆分它。我使用的正则表达式会将其拆分为空格或逗号。您可能需要尝试它才能根据您的不同输入获得有用的东西。
$street_array = preg_split('/['s*|,]/', strtoupper($street));
原始字符串为数组后,可以使用 array_intersect
返回与目标单词集匹配的任何单词。
$matches = array_intersect($streetTypes, $street_array);
然后,您可以使用匹配的单词执行任何操作。如果您只想显示一个匹配项,则应在$streetTypes
中优先考虑您的列表,以便最重要的匹配项排在第一位(如果有这样的事情)。然后,您可以使用以下命令显示它:
if ($matches) {
echo reset($matches);
}
(不应使用 $matches[0]
来显示第一个匹配项,因为键将保留在array_intersect
中,并且第一项可能没有索引零。
你需要这个:
$street = "100 road Overflow";
$streetTypes = array("ROAD", "ST", "ABBEY", "BLVD", "ALLEY", "CAR");
//find and save the street type in a variable
foreach($streetTypes as $item) {
$findType = strstr(strtoupper($street), $item);
if($findType){
$streetType = explode(' ', $findType)[0];
}
break;
}
if(isset($streetType)) {
echo "We have found ".$streetType." in the string";
} else {
echo "No have found street Type in the string";
}