Skip to content

Core\Regex\Match::groups

$match->groups(): array<?string>

Returns the text of every group of a match in one array.

The first entry is group 0, the whole match. The other groups follow in the order they start in the pattern. A group with a name is in the array twice: first under its name, then under its number.

A group that this match did not use is still in the array, and its value is null. So the array always has one entry for every group in the pattern, and you can tell an unused group from a group that matched an empty text.

Good to know: to read one group, group is shorter and throws an error for a group that does not exist.

The examples show the whole array, a named group that appears twice, and turning a line of text into named fields.

Return value

Returns array<?string>. An array with group 0 first. A group that this match did not use is in the array, and its value is null.

Examples

Every group at once

<?nvs
// Shows how to read every group of a match with one call.
// The pattern has three groups. `(:\d+)?` is optional and does not match here,
// so its value is `null`.
var $m = Core\Regex::match('https://example.com/shop', '(\w+)://([\w.]+)(:\d+)?');
if ($m != null) {
foreach ($m->groups() as string $key => ?string $text) {
echo $key, ': ', $text ?? 'null', "\n";
}
}
Output
0: https://example.com
1: https
2: example.com
3: null

A named group appears twice

<?nvs
// Shows that a group with a name is in the array under its name and under its number.
// The group `(?<user>\w+)` is group 1. The array has it as "user" and as "1".
var $m = Core\Regex::match('mail to ada@example.com', '(?<user>\w+)@([\w.]+)');
if ($m != null) {
array<?string> $all = $m->groups();
// This prints 4: the whole match, "user", 1 and 2.
echo Core\Arr::count($all), " entries\n";
foreach ($all as string $key => ?string $text) {
echo $key, ' = ', $text ?? 'null', "\n";
}
}
Output
4 entries
0 = ada@example.com
user = ada
1 = ada
2 = example.com

Turn a line into fields

<?nvs
// Shows how to turn a line of a settings file into named fields.
Core\Regex\Pattern $setting = Core\Regex::compile('^(?<key>[a-z_]+)\s*=\s*(?<value>.*?)\s*(?<comment>#.*)?$');
array<string> $lines = ['timeout = 30 # seconds', 'name=shop'];
foreach ($lines as string $line) {
var $m = Core\Regex::match($line, $setting);
if ($m != null) {
// A key that is a number is a group without a name. Only the named groups are printed.
foreach ($m->groups() as string $field => ?string $text) {
if (!Core\Regex::matches($field, '^\d+$')) {
echo $field, '=[', $text ?? 'none', '] ';
}
}
echo "\n";
}
}
Output
key=[timeout] value=[30] comment=[# seconds]
key=[name] value=[shop] comment=[none]