Skip to content

Core\Regex\Match::text

$match->text(): string

Returns the whole text that a pattern matched.

This is the same text as group 0. The result is never null, because every match has a whole text. It can be an empty string: a pattern such as \d* can match zero characters.

Use text when you need the matched part and not its groups. To read one part of the match, use group with the number or the name of the group.

The examples show reading a match, an empty match, and collecting every tag in a message.

Return value

Returns string. The matched text. It is never null, but it can be an empty string.

Examples

Read the matched text

<?nvs
// Shows how to read the text that a pattern matched.
// The pattern finds an amount of money. `text()` returns the whole match, "12.50 EUR".
var $m = Core\Regex::match('You paid 12.50 EUR today.', '\d+\.\d{2} [A-Z]{3}');
echo $m?->text() ?? 'no amount', "\n";
// `text()` returns the same text as `group(0)`. This prints "true".
echo $m?->text() == $m?->group(0) ? 'true' : 'false', "\n";
Output
12.50 EUR
true

An empty match

<?nvs
// Shows that a match can have an empty text.
// `\d*` also matches zero digits. "abc" starts with no digits, so the match
// is at position 0 and its text is empty.
var $m = Core\Regex::match('abc', '\d*');
if ($m != null) {
echo 'text: [', $m->text(), '], length ', Core\Str::length($m->text()), ', at ', $m->offset(), "\n";
}
// `\d+` needs at least one digit, so it finds "42".
echo '[', Core\Regex::match('abc42', '\d+')?->text() ?? 'none', "]\n";
Output
text: [], length 0, at 0
[42]

Collect the tags in a message

<?nvs
// Shows how to collect every tag, such as "#release", from a message.
string $message = 'Shipped #release 2.4 to #staging, see #release notes.';
// `matchAll` returns every match. `text()` gives the tag of each one.
array<string> $tags = [];
foreach (Core\Regex::matchAll($message, '#\w+') as Core\Regex\Match $m) {
$tags[] = $m->text();
}
// This prints "#release, #staging, #release".
echo Core\Str::join($tags, ', '), "\n";
Output
#release, #staging, #release