How to check if string contains a specific word in PHP?
In this article you will learn how to check if string contains a specific word, character and substring in PHP. You can simple usage of PHP strpos() function to check if string contains a specific word.
PHP strpos function
PHP strpos() function returns the position of the first occurrence of a substring in a string. It returns FALSE if the word or substring was not found. This means that you can the return value of strpos() to check for a substring.
Check if string contains a specific word in PHP
Example #1
The following example code snippet checks whether a specific word exists in the given string.
<?php
$string = "I am PHP developer.";
$word = "PHP";
if (strpos($string, $word) !== false) {
echo 'The word "'.$word.'" found in given string.';
} else {
echo 'The word "'.$word.'" not found in given string.';
}
?>
Output
The word "PHP" found in given string.
In above example i used the strict inequality operator (!==). If the word we are looking for occurs at the beginning of the string.
Example #2
The following example code snippet checks whether a specific substring exists in the given string.
<?php
$string = "I am PHP developer.";
$substring = "PHP developer";
if (strpos($string, $substring) !== false) {
echo 'The sub string "'.$substring.'" found in given string.';
} else {
echo 'The sub string "'.$substring.'" not found in given string.';
}
?>
Output
The sub string "PHP developer" found in given string.