What is the correct syntax for a regular expression to find multiple occurrences of the same string with preg_match in PHP?
For example find if the following string occurs 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";
}
preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
PHP | preg_match() Function. This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.
Definition and Usage The preg_match() function returns whether a match was found in a string.
You want to use preg_match_all()
. Here is how it would look in your code. The actual function returns the count of items found, but the $matches
array will hold 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";
}
?>
Will output:
2 matches found
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With