简体   繁体   中英

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:

$expression = '/foo/m';

Or remove the ^ if you don't mean to match the beginning of a line...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM