Home > Backend Development > PHP Tutorial > How Can I Find Multiple String Occurrences in PHP Using `preg_match_all`?

How Can I Find Multiple String Occurrences in PHP Using `preg_match_all`?

Mary-Kate Olsen
Release: 2024-11-28 13:30:14
Original
1074 people have browsed it

How Can I Find Multiple String Occurrences in PHP Using `preg_match_all`?

Identifying Multiple String Occurrences Using preg_match_all in PHP

The preg_match function in PHP allows for finding matches within a string, but it only identifies the first occurrence. To detect multiple occurrences of the same string, the preg_match_all function is the appropriate tool.

Consider the following example, where the goal is to determine if a specific string appears twice within a 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"
Copy after login

Using preg_match_all, the syntax would be as follows:

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

In this code, the preg_match_all function returns the number of matches identified within the paragraph. The $matches array stores the actual matches. When applied to the example above, it will output the following:

2 matches found
Copy after login

Therefore, preg_match_all is the preferred function for detecting multiple occurrences of a string in PHP, providing the count of matches and capturing the actual matches for further processing if necessary.

The above is the detailed content of How Can I Find Multiple String Occurrences in PHP Using `preg_match_all`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template