Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg match count matches

Tags:

regex

php

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

like image 236
Scarface Avatar asked Jun 17 '10 17:06

Scarface


People also ask

What does preg match mean?

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

What does preg match return?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

Is preg match case-insensitive?

preg_match is case sensitive. A match. Add the letter "i" to the end of the pattern string to perform a case-insensitive match.

What does Preg_match mean in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.


2 Answers

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

like image 176
Artefacto Avatar answered Nov 15 '22 15:11

Artefacto


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.

like image 33
webbiedave Avatar answered Nov 15 '22 13:11

webbiedave