2017-04-05 8 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 
) 
関連する問題