Menu

PHP: How to check if string contains specified word

This is the most common thing you need to takle while working with string in any programming language, not just PHP. There are some very easy solutions. The most common are written below. You can choose whichever suites you.

$string = 'Hello wOrld!';
$word_to_find = 'world';

Case Sensitive:

You can use PHP function mb_strpos to find whether specific word exists with same case in the string. 

if (mb_strpos($string, $word_to_find)) {
   echo 'Word exists';
}

This will return false. Because Word 'example' do exist but its case is different.

You can also use strpos instead of mb_strpos, but it is not multi-byte safe.

Case In-sensitive:

Or you can use PHP function mb_stripos. It works the same way as mb_strpos except, it ignores the case.

if (mb_stripos($string, $word_to_find)) {
    echo 'Word exists';
}

This will return true. Because mb_stripos match both strings ignoring case.

You can also use stripos instead of mb_stripos, but it is not multi-byte safe.