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
The preg_match() function returns whether a match was found in a string.
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 .
preg_match is case sensitive. A match. Add the letter "i" to the end of the pattern string to perform a case-insensitive match.
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.
$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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With