How to Check if a String Contains a Specific Word in PHP
In this short tutorial, we will provide you with the solution to one of the common issues in PHP: how to check whether a string contains a particular word.
This snippet will help you to check whether a string contains a specific word or not.
You can apply the <kbd class="highlighted">strpos()</kbd> 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, <kbd class="highlighted">false</kbd> is returned. But, the positions of the string begin from <kbd class="highlighted">0</kbd> and not <kbd class="highlighted">1</kbd>. For a better perception of this function, check out the example below:
php test string contains a word
There is a new function <kbd class="highlighted">str_contains()</kbd> in PHP 8 that provides the same functionality.
Using php8 function str_contains
Defining the Strpos() Function
The <kbd class="highlighted">strpos()</kbd> 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 <kbd class="highlighted">strpos()</kbd>. Among them are:
<kbd class="highlighted">strrpos():</kbd>aimed at detecting the position of a string’s last occurrence inside another string.<kbd class="highlighted">stripos():</kbd>aimed at detecting the position of a string’s first occurrence inside another string.<kbd class="highlighted">strripos():</kbd>aimed at detecting the position of a string’s last occurrence inside another string.