tags:

views:

37

answers:

4

Hey guys quick question, 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

+3  A: 

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.

webbiedave
Thanks webbie. Appreciate it.
Scarface
+6  A: 
$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.

Artefacto
Yeah you were right, I have to brush up on my regex skills. Thanks Art, appreciate the example.
Scarface
`\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
thanks salathe appreciate the input
Scarface
+3  A: 

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.

Matěj Grabovský
thanks matej appreciate it
Scarface
You're welcome.
Matěj Grabovský
+3  A: 

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

Manos Dilaverakis
yeah thats what the other guys recommended. Thanks Manos.
Scarface