Finding a word within a string with PHP

Finding a word within a string with PHPPutting a word into a variables or string, can open up a whole realm of new possibilities. With the following PHP code, we are going to find a word within a variable.

/// The following uses a 'Needle in a haystack' principle.
 $word = "PHP";
 $sentence = "PHP is such an elegant language.";

if(strstr($sentence, $word))
 echo "Found PHP within string";
 echo "Not found in string";

The native PHP strstr function looks for the $word value in the $sentence string. Note:┬áThe above example is case sensitive. If you wanted to perform this search as a case insensitive, substitute ‘strstr’ with ‘stristr’.

Leave a Reply

Your email address will not be published. Required fields are marked *