How to check if string contains specific word PHP

How to check if string contains specific word PHP

With PHP 8 there comes a default function by which we can check if string contains specific word or not.

// please note str_contains function is case-sensitive.
if (str_contains('Coding solutions point', 'solutions')) { 
    echo 'true';
}else{
    echo 'false';
}

Output : true


if (str_contains('Coding solutions point', 'Solutions')) { 
    echo 'true';
}else{
    echo 'false';
}

Output : false

For the lesser versions than php 8,below functions can be used.

// strpos() - case sensitive search
 
if (strpos('Coding solutions point', 'solutions') !== false) {
    echo 'true';
}else{
   echo 'false';
}
Output : true

if (strpos('Coding solutions point', 'Solutions') !== false) {
    echo 'true';
}else{
   echo 'false';
}
Output : false

The other function which can be used is stripos() which perform case insensitive search.

// stripos() - case insensitive search
if (stripos('Coding solutions point', 'Solutions') !== false) {
    echo 'true';
}else{
   echo 'false';
}
Output : true

Please check the use of !== false is deliberate (neither != false nor === true will work)