PHP - 使用一组针搜索文本正文,返回所有匹配的键

时间:2017-04-05 17:05:18

标签: php arrays string preg-match

要搜索文本正文并返回在文本中找到的任何数组元素的键。我目前有下面的工作,但只在找到的第一个元素上返回True。

$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car'];
$text = "Does anyone know how much Bentleys charge to put up a small shed please? Thanks";

if(preg_match('/'.implode('|', array_map('preg_quote', $needles)).'/i', $text)) {
    echo "Match Found!";
}

然而我需要的输出是

[1 => 'shed', 5 => 'charge']

有人可以帮忙吗?我将搜索大量值,因此需要使用preg_match来快速解决。

1 个答案:

答案 0 :(得分:1)

使用array_filterpreg_match函数的解决方案:

$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car'];
$text = "Does anyone know how much Bentleys charge to put up a small shed please? Thanks";

// filtering `needles` which are matched against the input text
$matched_words = array_filter($needles, function($w) use($text){
    return preg_match("/" . $w . "/", $text);
});

print_r($matched_words);

输出:

Array
(
    [1] => shed
    [5] => charge
)