2017-04-05 90 views
1

尋找搜索文本主體並返回文本中找到的任何數組元素的鍵。我目前有下面的工作,但只發現第一個元素返回True。PHP - 用一列針搜索文本主體,返回所有匹配的鍵

$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

使用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 
) 
相關問題