[wd_asp elements=’search’ ratio=’100%’ id=1]

Search for multiple words in a string – PHP

14th February 2020

Php - Strings

php codehaven

If you want to find one word in a string you would use strpos, but there can be a problem when you want to search for more than one word, then this code below would work for you.

function contains($needles, $haystack) {
return count(array_intersect($needles, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
}

$string = 'site security';
$array = array('building', 'site','security');
$i = contains($array, $string);
echo ($i) ? "Keyword found" : "not found";