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

时间:2010-10-13 05:42:24

标签: php regex

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

单词列表示例

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分: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

答案 2 :(得分:0)

请务必添加“m”标记,以使^匹配一行的开头:

$expression = '/foo/m';

如果您不想匹配行的开头,请删除^