Skip to main content

Capturing groups update

One update about groups, not to cause confusion. $match->groups() treats indexes a bit different than $match->group(int). Read on to learn more :)

Anyone who worked with regular expressions knows, that group 0 is a whole match. I don't want to break that convention. That is why I assumed that they must be equal:

$match->group(0) === $match->text()

Having said that, I still want to distinguish a method which returns groups and the one that returns a whole match. So $match->groups() doesn't return the whole match at index 0, while $match->group() does.

You can think of $this->group(int) method as:

return [$this->text(), ...$this->groups()];

So...

$match->group(0) == $match->text();
$match->group(1) == $match->groups()[0];
$match->group(2) == $match->groups()[1];
$match->group(3) == $match->groups()[2];
$match->group(4) == $match->groups()[3];

And a quick update about the CleanRegex:

  • I added a ReadMeTest testcase, which asserts that all code used in ReadMe.md has the presented results.
  • New ->first(), ->all() and ->only() methods to explicitly match/replace certain amount of occurrences. This will also be used with capturing groups.