Count occurrences
Sometimes, you might stumble upon a situation where an amount of occurrences is needed, but not the occurrences
themselves. In that case, pattern()->count()
is perfect:
- T-Regx
- PHP
Also, MatchPattern
is \Countable
, so you can use PHP build-in methods, like count()
:
- T-Regx
- PHP
#
Unmatched subjectsIf your pattern does not match the subject, count()
simply returns 0
.
- T-Regx
- PHP
#
InvalidEvery use of pattern()
with an invalid pattern will cause MalformedPatternException
.
- T-Regx
- PHP
note
In PHP
snippet, MalformedPatternException
is thrown because SafeRegex preg::match_all()
was used, instead
of preg_match_all()
. Vanilla PHP preg
methods don't throw exceptions.
#
PerformanceYou might be tempted to use count()
to check whether your subject was matched by the pattern, since count()
doesn't
return any matches...
- T-Regx
- PHP
...but that would be wasteful. You're much better off using
test()
/fails()
:
- T-Regx
- PHP
This is because count()
will go through each occurrence of a pattern in a subject, counting it; whereas test()
will return right after it finds the first occurrence.
note
Under the hood, count()
uses preg_match_all()
, whereas test()
/fails()
use preg_match()
.