Home >Backend Development >PHP Tutorial >How to efficiently find word occurrences in a string using PHP?
Finding Word Occurrences in a String with PHP
Question:
How can you determine if a specific word exists within a given string?
Answer:
PHP provides several methods to check for word occurrences:
strpos() and stripos() Functions:
These functions search for the first occurrence of a string within another string. If found, they return the character index of the match. If not, they return false. To check for existence, compare the return value with false:
<code class="php">$needle = 'to'; $haystack = 'I go to school'; if (strpos($haystack, $needle) !== false) { echo 'Found!'; }</code>
strstr() and stristr() Functions:
These functions return the part of the haystack after the first occurrence of the needle. If the needle is not found, they return false. To check for existence, check if the returned value is not false:
<code class="php">if (strstr($haystack, $needle)) { echo 'Found!'; }</code>
preg_match() Function:
Preg_match uses regular expressions to find matches. It returns 1 for a successful match, 0 for no match, or false in case of an error. To check for existence, compare the return value with 1:
<code class="php">if (preg_match('/to/', $haystack)) { echo 'Found!'; }</code>
str_contains() Function (PHP 8.0 ):
Introduced in PHP 8.0, this function directly checks if one string contains another. It returns true if the needle is found, and false otherwise:
<code class="php">if (str_contains($haystack, $needle)) { echo 'Found!'; }</code>
For simplicity and directness, strpos() is a suitable choice for this purpose. If additional operations need to be performed on the result, strstr() or preg_match() may be more appropriate. For precise pattern matching, preg_match() provides greater flexibility.
The above is the detailed content of How to efficiently find word occurrences in a string using PHP?. For more information, please follow other related articles on the PHP Chinese website!