preg match count matches
preg_match already returns the number of times the pattern matched.
However, this will only be 0 or 1 as it stops after the first match. You can use preg_match_all instead as it will check the entire string and return the total number of matches.
You should use preg_match_all
if you want to match all occurences. preg_match_all
returns number of matches. preg_match
returns only 0 or 1, because it matches only once.
$message='[tag] [tag]';
echo preg_match_all('/\\[tag\\](?>\\s|$)/i', $message, $matches);
gives 2
. Note you cannot use \b
because the word boundary is before the ]
, not after.
See preg_match_all.