Home >Backend Development >PHP Tutorial >How Can I Check if a String Contains a Specific Word in PHP?
How to Check if a String Contains a Specific Word
In PHP, determining whether a string contains a particular word can be achieved through various methods.
PHP 8 and str_contains
With PHP 8, the str_contains function can be used:
if (str_contains('How are you', 'are')) { echo 'true'; }
Note that str_contains returns true even if the searched substring ($needle) is empty. To prevent this, ensure that $needle is not empty before the check:
$haystack = 'How are you?'; $needle = ''; if ($needle !== '' && str_contains($haystack, $needle)) { echo 'true'; }
Pre-PHP 8 and strpos
Prior to PHP 8, the strpos function can be used:
$haystack = 'How are you?'; $needle = 'are'; if (strpos($haystack, $needle) !== false) { echo 'true'; }
Considerations
The above is the detailed content of How Can I Check if a String Contains a Specific Word in PHP?. For more information, please follow other related articles on the PHP Chinese website!