PHP preg_match for finding multiple occurrences

What is the correct regex syntax for finding multiple occurrences of the same string with preg_match in PHP?

For example, find the following line: TWICE in 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" if (preg_match($string, $paragraph)) { echo "match found"; }else { echo "match NOT found"; } 
+7
php preg-match
source share
1 answer

You want to use preg_match_all() . This is how it will look in your code. The actual function returns the number of elements found, but the $matches array will contain the results:

 <?php $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"; } ?> 

It will display:

Found 2 matches

+23
source share

All Articles