1

Looking to search a body of text and return the keys of any of the array elements that have been found within the text. I currently have the below which works but only returns True on the first element found.

$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!";
}

However the output I need is;

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

Can anybody help? I am going to be searching a lot of values so this needs to be a fast solution hence using preg_match.

Abanoub Makram
  • 463
  • 2
  • 13
Kieran Headley
  • 647
  • 1
  • 7
  • 21

1 Answers1

1

The solution using array_filter and preg_match functions:

$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);

The output:

Array
(
    [1] => shed
    [5] => charge
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105