18

I have a preg match statement, and it checks for matches, but I was wondering how you can count the matches. Any advice appreciated.

$message='[tag] [tag]';
preg_match('/\[tag]\b/i',$message);

for example a count of this message string should lead to 2 matches

5 Answers 5

35
$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.

2
  • 1
    Yeah you were right, I have to brush up on my regex skills. Thanks Art, appreciate the example.
    – Scarface
    Jun 17, 2010 at 17:49
  • 2
    \b could be used, it would just affect what is matched (i.e. the [tag] would need to be followed by a word character).
    – salathe
    Jun 17, 2010 at 17:59
17

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.

1
  • Point for explaining the difference between the two functions. May 25, 2018 at 15:34
4

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.

0
4

I think you need preg_match_all. It returns the number of matches it finds. preg_match stops after the first one.

1
  • yeah thats what the other guys recommended. Thanks Manos.
    – Scarface
    Jun 17, 2010 at 17:49
1

You could use T-Regx library with count() method (and even automatic delimiters):

$count = pattern('\[tag]\b', 'i')->match('[tag] [tag]')->count();

$count // 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.