2010-10-13 151 views
1

我有一個數組中的單詞列表。我需要在字符串上查找任何這些單詞的匹配。PHP正則表達式匹配一個字符串列表

示例單詞列表

company 
executive 
files 
resource 

例串

Executives are running the company 

下面是我寫的功能,但它不工作

$matches = array(); 
$pattern = "/^("; 
foreach($word_list as $word) 
{ 
    $pattern .= preg_quote($word) . '|'; 
} 

$pattern = substr($pattern, 0, -1); // removes last | 
$pattern .= ")/"; 

$num_found = preg_match_all($pattern, $string, $matches); 

echo $num_found; 

輸出

0 
+1

你對這個例子期望輸出什麼? – Gumbo 2010-10-13 06:20:34

回答

5
$regex = '(' . implode('|', $words) . ')'; 
+4

如果你不能控制單詞,你可能應該''array_map()''通過'preg_quote()'。 – alex 2010-10-13 06:18:04

+1

@alex但是這將是兩行。 – amphetamachine 2010-11-01 03:45:45

+0

我認爲兩條線是一個小的代價,可以與任何用戶輸入的字符串兼容:P – alex 2010-11-01 06:07:45

0

請務必添加「M」標誌,使^匹配行的開頭:

$expression = '/foo/m'; 

或刪除^,如果你不是說要匹配行的開頭...

1
<?php 

$words_list = array('company', 'executive', 'files', 'resource'); 
$string = 'Executives are running the company'; 

foreach ($words_list as &$word) $word = preg_quote($word, '/'); 

$num_found = preg_match_all('/('.join('|', $words_list).')/i', $string, $matches); 
echo $num_found; // 2