PHP正则表达式匹配字符串的单词列表

Hyd*_*erA 2 php regex

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

示例单词列表

company
executive
files
resource
Run Code Online (Sandbox Code Playgroud)

示例字符串

Executives are running the company
Run Code Online (Sandbox Code Playgroud)

这是我写的功能,但它不起作用

$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;
Run Code Online (Sandbox Code Playgroud)

产量

0
Run Code Online (Sandbox Code Playgroud)

amp*_*ine 5

$regex = '(' . implode('|', $words) . ')';
Run Code Online (Sandbox Code Playgroud)

  • 如果你无法控制单词,你可能应该通过`preg_quote()`来`array_map()`. (4认同)