Home >Backend Development >PHP Tutorial >How Can I Find All Occurrences of a String Pattern in PHP?

How Can I Find All Occurrences of a String Pattern in PHP?

DDD
DDDOriginal
2024-12-04 09:28:12944browse

How Can I Find All Occurrences of a String Pattern in PHP?

Finding Multiple String Occurrences with PHP's preg_match

In PHP, the preg_match function can be utilized to search for specific text patterns within strings. However, to locate multiple instances of the same pattern, a slightly different approach is required.

The solution lies in employing the preg_match_all() function instead of preg_match. This advanced function returns an array containing all the matching instances found within the input string, enabling us to determine their count.

Consider the following example:


$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";

if (preg_match_all($string, $paragraph, $matches)) {
echo count($matches[0]) . " matches found";
} else {
echo "match NOT found";
}

In this example, the preg_match_all() function is utilized to search for multiple occurrences of the pattern "/brown fox jumped [0-9]/" within the given paragraph. The function will return an array named $matches, which contains all the found instances. By counting the number of elements in $matches[0], we can determine the number of matches.

Executing this code will output:


2 matches found

This demonstrates that the pattern "/brown fox jumped [0-9]/" appears twice within the paragraph.

The above is the detailed content of How Can I Find All Occurrences of a String Pattern in PHP?. 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