PHP - searching a body of text with an array of needles, returning the keys of all matches -


looking search body of text , return keys of of array elements have been found within text. have below works returns true on first element found.

$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car']; $text = "does know how bentleys charge put small shed please? thanks";  if(preg_match('/'.implode('|', array_map('preg_quote', $needles)).'/i', $text)) {     echo "match found!"; } 

however output need is;

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

can help? going searching lot of values needs fast solution hence using preg_match.

the solution using array_filter , preg_match functions:

$needles = [1 => 'shed', 5 => 'charge', 8 => 'book', 9 => 'car']; $text = "does know how bentleys charge put small shed please? thanks";  // filtering `needles` matched against input text $matched_words = array_filter($needles, function($w) use($text){     return preg_match("/" . $w . "/", $text); });  print_r($matched_words); 

the output:

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

Comments