Skip to content
mck89 edited this page Mar 18, 2015 · 1 revision

Subpatterns

Subpatterns are containers that group pattern. In REBuilder they are instances of REBuilder\Pattern\SubPattern class and can be added using addSubPattern method.

$regex
      ->addSubPattern()
            ->addChar("a")

echo $regex; // "/(a)/"

Both class constructor and addSubPattern method take 5 arguments that identify the type of subpattern to create:

  • Capture: a boolean that indicates if the supattern is a capturing subpattern, this means that its match will be stored when the regex is executed. By default the capture flag is true, setting it to false creates a non capturing subpattern and its match won't be stored.
  • Name: a string that indicates the name of the subpattern. If you assign a name to a subpattern its match will be stored with the given name.
  • Modifiers: a string that indicates the pattern modifiers, these modifiers will be valid only for the content of the subpattern.
  • GroupMatches: a boolean that, if set to true and if the subpattern contains an alternation group, indicates that matches on different alternations will be stored at the same index.
  • OnceOnly: a boolean that, if set to true, improves regex performances is some cases (to better understand this refer to PHP documentation).

Note that since every argument, if set, is incompatible with all the others, if you set more than one argument, the subpattern will be rendered as a set of nested subpatterns.

Back References

Inside the regex you can refer to the match of a capturing subpattern using back references. To add a back reference you can do:

$regex
      ->addSubPattern()
            ->addCharAndContinue("a")
      ->getParent()
      ->addBackReference("1");

echo $regex; // "/(a)\1/"

Both the REBuilder\Pattern\BackReference class constructor and addBackReference takes one argument that is the index or the name of the subpattern to which they refer.

Clone this wiki locally