[英]PHP Regex to match a list of words against a string
I have a list of words in an array. 我有一个数组中的单词列表。 I need to look for matches on a string for any of those words. 我需要为这些单词中的任何一个寻找匹配项。
Example word list 单词列表示例
company
executive
files
resource
Example string 字符串示例
Executives are running the company
Here's the function I've written but it's not working 这是我编写的功能,但无法正常工作
$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;
Output 产量
0
$regex = '(' . implode('|', $words) . ')';
<?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
Make sure you add the 'm' flag to make the ^
match the beginning of a line: 确保添加'm'标志以使^
匹配行的开头:
$expression = '/foo/m';
Or remove the ^
if you don't mean to match the beginning of a line... 或者,如果您不想匹配行的开头,请删除^
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.