Counting Matches in a String
Problem
You want to find out how many times a particular pattern occurs in a string.
Solution
Use PHP’s preg_match_all() function:
<?php
// define string
$html = “I’m <b>tired</b> and so I <b>must</b> go
<a href=’http://domain’>home</a> now”;
// count occurrences of bold text in string
// result: “2 occurrence(s)”
preg_match_all(“/<b>(.*?)<\/b>/i”, $html, &$matches);
echo sizeof($matches[0]) . ” occurrence(s)”;
?>
Comments
The preg_match_all() function tests a string for matches to a particular pattern,
and returns an array containing all the matches. If you need the total number of
matches, simply check the size of the array with the sizeof() function.
For simpler applications, also consider the substr_count() function, which
counts the total number of occurrences of a substring within a larger string. Here’s
a brief example:
<?php
// define string
$text = “ha ha ho hee hee ha ho hee hee ho ho ho ha hee”;
// count occurrences of “hee ” in string
// result: “5 occurrence(s)”
echo substr_count($text, “hee”) . ” occurrence(s)”;
?>