Home >Backend Development >PHP Tutorial >How Do I Check if a String Contains a Specific Word in PHP?
How to Determine if a String Contains a Particular Word
In programming, it is often necessary to check whether a string contains a specific word or substring. One common way to do this is using the if statement, as demonstrated in your code excerpt:
$a = 'How are you?'; if ($a contains 'are') echo 'true';
However, the code above won't work because there is no built-in "contains" method for strings in PHP. To correctly write this statement, we can use alternative methods.
PHP 8 and Later
PHP 8 introduces the str_contains function, which simplifies checking for substring existence:
if (str_contains('How are you', 'are')) { echo 'true'; }
Before PHP 8
Prior to PHP 8, you can use the strpos() function to find the occurrence of a substring:
$a = 'How are you?'; $needle = 'are'; if (strpos($a, $needle) !== false) { echo 'true'; }
Here, strpos() searches for the position of the substring, and a non-false result indicates its presence.
Additional Notes
The above is the detailed content of How Do I Check if a String Contains a Specific Word in PHP?. For more information, please follow other related articles on the PHP Chinese website!