How to Check if a String Contains a Specific Word in PHP
This snippet will help you to check whether a string contains a specific word or not.
You can apply the strpos() function for checking if a string contains a certain word.
This function is capable of returning the position of the first occurrence of a substring inside a string. In the case of not detecting the substring, false is returned. But, the positions of the string begin from 0 and not 1. For a better perception of this function, check out the example below:
<?php
$word = 'fox';
$myString = 'The quick brown fox jumps over the lazy dog';
// Test whether the string contains the word
if (strpos($myString, $word) !== false) {
echo "Word Found!";
} else {
echo "Word Not Found!";
}
?>
There is a new function str_contains() in PHP 8 that provides the same functionality.
<?php
$word = 'fox';
$myString = 'The quick brown fox jumps over the lazy dog';
// Test whether the string contains the word
if (str_contains($myString, $word)) {
echo 'Word Found!';
} else {
echo 'Word Not Found!';
}
Defining the Strpos() Function
The strpos() function helps to detect the position of the first occurrence of a string inside another one.
This function is considered case-sensitive and binary-safe.
Also, you can meet functions relative to strpos(). Among them are:
- strrpos(): aimed at detecting the position of a string’s last occurrence inside another string.
- stripos(): aimed at detecting the position of a string’s first occurrence inside another string.
- strripos(): aimed at detecting the position of a string’s last occurrence inside another string.