Skip to content

Core\Regex::matchAll

Finds every place where a pattern matches a text, and returns the matches in an array.

Each item in the array is a Core\Regex\Match, in the order the matches appear in the text. A Match has the matched text, the position where it starts, and the text of each group in the pattern. Matches do not overlap: the next search starts where the previous match ends. If the pattern matches nowhere, the array is empty. Positions count characters, not bytes.

Good to know: to find only the first match, use Core\Regex::match. It stops after one match, so it is faster on a long text.

Parameters

  • $subjectstringThe text to search.
  • $patternCore\Regex\Pattern|stringA Core\Regex\Pattern from Core\Regex::compile, or a pattern string with no options. A tainted string does not compile here.

Return value

Returns array<Core\Regex\Match>. One Core\Regex\Match for each match, from left to right. The array is empty if there is no match.

Errors

  • RuntimeError$pattern is not a valid regular expression, or matching it against $subject needs more steps than the limit allows.

Examples

Every number

<?nvs
// Shows how to find every number in a text, with the position of each one.
string $text = 'Rooms 12, 7 and 104 are free.';
// `matchAll` returns one `Core\Regex\Match` for each number, from left to right.
// This prints "12 at 6", then "7 at 10", then "104 at 16".
foreach (Core\Regex::matchAll($text, '\d+') as Core\Regex\Match $number) {
echo $number->text(), ' at ', $number->offset(), "\n";
}
Output
12 at 6
7 at 10
104 at 16

No match is an empty array

<?nvs
// Shows that `matchAll` returns an empty array when the pattern matches nowhere.
array<string> $lines = ['Contact: help@example.com, sales@example.com', 'No address here.'];
// The first line has two addresses, so this prints 2.
// The second line has none. The array is empty, so this prints 0.
foreach ($lines as string $line) {
var $found = Core\Regex::matchAll($line, '[a-z]+@[a-z.]+');
echo Core\Arr::count($found), ' address(es) in: ', $line, "\n";
}
Output
2 address(es) in: Contact: help@example.com, sales@example.com
0 address(es) in: No address here.

Read key value pairs from a log line

<?nvs
// Shows how to read every `key=value` pair from a log line into an array.
string $line = 'status=200 method=GET path=/orders time_ms=35';
// Each match has two named groups: `key` and `value`.
// `group("key")` reads the text of one group by its name.
Core\Regex\Pattern $pair = Core\Regex::compile('(?<key>\w+)=(?<value>\S+)');
array<string> $fields = [];
foreach (Core\Regex::matchAll($line, $pair) as Core\Regex\Match $one) {
$fields[$one->group('key') ?? ''] = $one->group('value') ?? '';
}
// This prints "GET /orders took 35 ms".
echo $fields['method'], ' ', $fields['path'], ' took ', $fields['time_ms'], " ms\n";
Output
GET /orders took 35 ms