Apart from retrieving matched capturing groups, you can also replace by an inline group.
match()->group() behaves exactly like
- it can accept either group index (where #0 is the whole match) or a group name (when a group is named)
- it throws
\InvalidArgumentExceptionfor an invalid index or an invalid group name (e.g.
- and throws
group()is used with a non-existent group
Matched occurrences of a group
Similarly to how you can retrieve all matched occurrences of pattern from subject:
...you can retrieve all matched occurrences of a capturing group in a subject:
match()->group()->all() also handle optional capturing groups.
In this example, we'll match words, with a pattern that specifies an optional capturing group named
is supposed to match a capital letter. Not every word in the subject has a capital letter, so not every occurrence will
Missing or invalid groups
match()->group() is called with a group that wasn't used in pattern (for example
NonexistentGroupException is thrown.CodeTabs
If, however, an invalid group is used:
- group name starting with a number (e.g.
- negative group index (e.g.
- group name containing invalid characters (e.g.
\InvalidArgumentException is thrown.