PHP正则表达式将单词列表与字符串进行匹配

PHP正则表达式将单词列表与字符串进行匹配,php,regex,Php,Regex,我有一个数组中的单词列表。我需要在字符串中查找这些单词的匹配项 示例词表 company executive files resource 示例字符串 Executives are running the company 这是我写的函数,但它不起作用 $matches = array(); $pattern = "/^("; foreach( $word_list as $word ) { $pattern .= preg_quote( $word ) . '|'; } $patt

我有一个数组中的单词列表。我需要在字符串中查找这些单词的匹配项

示例词表

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

确保添加“m”标志以使
^
与行首匹配:

$expression = '/foo/m';

或者删除
^
如果您不想匹配行首…

如果您无法控制单词,您可能应该通过
preg\u quote()来
array\u map()
@alex,但那将是两行。我认为两行是一个小代价,可以让它与任何用户输入的字符串兼容:P@alex如果您使用的是Perl,则不会。但是问题被标记为[php]。对于这个示例,您希望得到什么样的输出?
<?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
<?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