Skip to main content

Counting occurrences

Documentation for version: 0.41.2

In certain situations an amount of occurrences is desired, but not the occurrences themselves. In that case, it's recommended to consider Pattern.count(), instead of performing full matches with Matcher.all()/Search.all().

Method Pattern.count() accepts a string subject, and returns the number of occurrences of the pattern in the subject.

/*
* Instantiate pattern
*/
$pattern = pattern('[aeiouy]');
/*
* Count occurrences
*/
$pattern->count('Computer'); // (int) 3

Unmatched subjects#

When Pattern.count() is called with a subject that doesn't match the pattern, then count() returns 0.

$pattern = Pattern::of('[0-9]');
$pattern->count('Computer'); // (int) 0

Malformed patterns#

Every use of pattern()/Pattern::of() with an invalid pattern causes MalformedPatternException.

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

Number of occurrences in Matcher#

Apart from Pattern.count(), methods Matcher.count() and Search.count() can also be used to retrieve the number of occurrences of the pattern in the subject.

/*
* Instantiate pattern
*/
$pattern = pattern('[aeiouy]');
/*
* Instantiate the subject matcher
*/
$matcher = $pattern->match('Computer');
/*
* Count occurrences
*/
$matcher->count(); // (int) 3

Additionally, Matcher implements PHP interface \Countable, and so can be used with PHP methods, such as count():

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

Performance predicating a subject#

It might appear suitable to use count() to ascertain whether a given subject matches the pattern, since count() doesn't return any matches.

$pattern = Pattern::of('[aeiouy]');
$count = $pattern->count('Computer');
return $count > 0; // (bool) true

While that is true, that using Pattern.count() is more performant than Matcher.all(), it still iterates all of the occurrences of the pattern in the subject.

The recommended approach for such predication is with test()/fails():

$pattern = Pattern::of('[aeiouy]');
return $pattern->test('Computer'); // (bool) true

That's because count() goes through each occurrence of a pattern in the subject counting it, whereas test() returns right after matching the first occurrence.

Last updated on