Skip to content
Advertisement

How to search for certain words in array in a sentence using PHP

I am trying to search for certain word in a sentence. To that effect, I leverage solutions found (source), which works fine for searching just a word.

My issue is that I need to search the words in the array in a sentence something like

$findme = array("food", "water", "salt");

How can I do that?

Here is the code:

$mystring = 'my best food is Jellof Rice';


$findme   = 'food';
$pos = strpos($mystring, $findme);

if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'.";
}
else {
    echo "The string '$findme' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}

Advertisement

Answer

try something like this one

$mystring = 'text goes here';
$Found = false;
$findme = array("food", "water", "salt");
foreach($findme  as $singleValue ){
 if ($strpos($mystring, $singleValue ) != false) {
   $Found = true;
 }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement