Home >Backend Development >PHP Tutorial >How Can I Find All Occurrences of a String in PHP Using `preg_match_all()`?
Finding Multiple Occurrences with preg_match_all in PHP
Question:
How to utilize PHP's preg_match to identify multiple occurrences of a specific string within a given text?
Example:
Suppose we want to determine whether the string "/brown fox jumped [0-9]/" appears twice within the following paragraph:
$string = "/brown fox jumped [0-9]/"; $paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence.";
Answer:
While preg_match can detect the first occurrence of a string, to locate multiple occurrences, we must use the preg_match_all() function. The corrected code using preg_match_all() is below:
if (preg_match_all($string, $paragraph, $matches)) { echo count($matches[0]) . " matches found"; } else { echo "match NOT found"; }
In this code, $matches is an array that contains all the matches found. The count($matches[0]) expression returns the number of matches.
Output:
This code will produce the following output since the given string appears twice within the paragraph:
2 matches found
The above is the detailed content of How Can I Find All Occurrences of a String in PHP Using `preg_match_all()`?. For more information, please follow other related articles on the PHP Chinese website!