2011-06-14 91 views
6

在SO的幫助下,我能夠從電子郵件主題行中拉出「關鍵字」以用作類別。現在我決定允許每個圖片有多個類別,但似乎無法正確說出我的問題以獲得Google的良好回覆。 preg_match停在列表中的第一個單詞處。我確信這與'急於'或簡單地用別的東西代替管道符號|有關,但我只是看不到它。
\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b使用preg_match查找列表中的所有單詞

我目前使用的整個字符串爲:

preg_match("/\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b/i", "." . $subject . ".", $matches);

所有我需要做的就是把所有的這些話,如果他們存在,而不是在阿姆斯特丹停止,或任何字它首先在它正在搜索的主題中。之後,這只是處理$ matches數組的問題,對吧?

謝謝, 馬克

+5

嘗試'preg_match_all' - http://php.net/manual/en/function.preg-match-all.php - 只需將'_all'添加到函數名稱。 – hakre 2011-06-14 23:09:50

+2

我還會補充說'$ matches'有一些變化,有'preg_match_all' – datasage 2011-06-15 01:23:21

+0

非常感謝!是的,$匹配確實會改變。乍一看,現在似乎是一個數組內的數組。 'print_r($ matches)'給了'Array([0] => Array([0] => paris [1] => bulle))''。我正在研究它,但有關處理這個問題的明顯建議? – Mark 2011-06-15 02:42:55

回答

1

好了,這裏有preg_match_all()一些示例代碼,顯示如何刪除嵌套還有:

$pattern = '\b(?:amsterdam|paris|zurich|munich|frankfurt|bulle)\b'; 
$result = preg_match_all($pattern, $subject, $matches); 

# Check for errors in the pattern 
if (false === $result) { 
    throw new Exception(sprintf('Regular Expression failed: %s.', $pattern)); 
} 

# Get the result, for your pattern that's the first element of $matches 
$foundCities = $result ? $matches[0] : array(); 

printf("Found %d city/cities: %s.\n", count($foundCitites), implode('; ', $foundCities)); 

由於$foundCities現在是一個簡單的數組,你可以遍歷它直接也是如此:

foreach($foundCities as $index => $city) { 
    echo $index, '. : ', $city, "\n"; 
} 

不需要嵌套循環,因爲$matches返回值有蜜蜂已經規範化了。這個概念是讓代碼根據需要返回/創建數據以供進一步處理。

+0

非常感謝您的額外幫助!這爲我清除了很多東西。我知道有一個合適的方法來做到這一點。 – Mark 2011-06-15 19:17:33

相關問題