2016-02-22 111 views
0

我有一個包含地址的字符串,我需要知道該地址正在使用哪種街道類型。下面是一個例子:在地址中獲取街道類型

$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 

解決此問題的最佳方法是什麼?

+0

這裏是一個回答已發佈:http://stackoverflow.com/questions/13795789/check-if-string-contains-word-in-array。不完全是你需要的,但非常接近 –

回答

0

與您的字符串開始,和組詞您正在尋找:

$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被保留,並在第一個項目可能沒有指數爲零。)

0

你需要這樣的:

$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"; 
}