Checking String for Specific Word
The task of checking whether a string contains a particular word is a common operation in programming. Consider the following code:
$a = 'How are you?'; if ($a contains 'are') echo 'true';
What is the correct way to write the statement if ($a contains 'are')?
Solution: str_contains Function (PHP 8)
From PHP 8 onwards, str_contains provides a straightforward solution:
if (str_contains('How are you', 'are')) { echo 'true'; }
However, it's important to note that str_contains always returns true if the substring to search for ($needle) is empty. To avoid this, verify that $needle is non-empty before using str_contains.
Alternatives (Pre-PHP 8)
Before PHP 8, the strpos() function was used for this purpose:
$haystack = 'How are you?'; $needle = 'are'; if (strpos($haystack, $needle) !== false) { echo 'true'; }
In this case, strpos() returns the position of the $needle within the $haystack, or false if not found. However, using !== false is necessary since 0 is a valid position and also evaluates to falsey.
The above is the detailed content of How Can I Efficiently Check if a String Contains a Specific Word in PHP?. For more information, please follow other related articles on the PHP Chinese website!