2010-10-13 155 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