How to check if a string contains a specific word in PHP?

If we want to check a specific word contains in another string. It’s common this kind of requirement while developing projects in PHP.

We can use strpos function which is used to find the occurrence of one string inside other:

$str = 'How are you buddy?';
if (strpos($str, 'are') !== false) {
echo 'true';

You notice that I used the check against the false as strpos returns the string occurrence number in another string. Since 0 is a number we can’t ¬†use like this !(strpos($str, ‘are’) this will give the wrong result.

Editorial Staff

Editorial Staff at tutsplanet is a dedicated team to write various tutorial articles.