Checking String Contains Specific Word
In PHP, verifying if a string contains a particular word can be achieved using built-in functions or string manipulation techniques.
Using str_contains (PHP 8 )
PHP 8 introduces the str_contains function for checking string containment:
if (str_contains('How are you', 'are')) { echo 'true'; }
Note: str_contains considers an empty needle as true, so ensure it's not empty before using it.
Using strpos
For PHP versions prior to 8, strpos can be employed:
$haystack = 'How are you?'; $needle = 'are'; if (strpos($haystack, $needle) !== false) { echo 'true'; }
Using strstr
Another option is to use strstr:
if (strstr('How are you?', 'are') !== false) { echo 'true'; }
Using Regular Expressions
Regular expressions can also be used:
if (preg_match('/are/', 'How are you?')) { echo 'true'; }
The above is the detailed content of How Can I Check if a PHP String Contains a Specific Word?. For more information, please follow other related articles on the PHP Chinese website!