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:

return pattern('[aeiouy]')->count('Computer');
3

Also, MatchPattern is \Countable, so you can use PHP build-in methods, like count():

$match = pattern('[aeiouy]')->match('Computer');
count($match);
3

Unmatched subjects#

If your pattern does not match the subject, count() simply returns 0.

return pattern('[0-9]')->count('Computer');
0

Invalid#

Every use of pattern() with an invalid pattern will cause MalformedPatternException.

try {
pattern('[aeiouy')->count('Computer'); // malformed pattern
}
catch (MalformedPatternException $ex) {
echo $ex->getMessage();
}
Missing terminating ] for character class at offset 7
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.

Performance#

You might be tempted to use count() to check whether your subject was matched by the pattern, since count() doesn't return any matches...

$count = pattern('[aeiouy]')->count('Computer');
return $count > 0;
true

...but that would be wasteful. You're much better off using test()/fails():

return pattern('[aeiouy]')->test('Computer');
true

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().

Last updated on