Home >Backend Development >PHP Tutorial >How Can I Find All Occurrences of a String in PHP Using `preg_match_all()`?

How Can I Find All Occurrences of a String in PHP Using `preg_match_all()`?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 00:24:10742browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn