Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match to find multiple occurrences

Tags:

php

preg-match

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";
}
like image 814
Marcus Avatar asked Jan 08 '10 19:01

Marcus


People also ask

What is the difference between Preg_match and Preg_match_all?

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.

What is the use of Preg_match in PHP?

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.

What does Preg_match return in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.


1 Answers

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

like image 84
Doug Neiner Avatar answered Sep 16 '22 19:09

Doug Neiner