Skip to main content

First occurrence

Matching a first occurrence in a string is the most common use-case.

About first()#

You can get the first occurrence of a pattern in a subject by calling first().

pattern('[0-9]+')->search("I'm 19 years old")->first();
'19'

Match details#

With Detail and match(), you can gain access to useful information about the matched occurrence.

$detail = pattern('\w+')->match("Apples are cool")->first();
$subject = $detail->subject();
echo "Match '$detail' was matched inside '$subject'.";
Match 'Apples' was matched inside 'Apples are cool'.

You can read more extensively about it on Detail page.

Groups in match#

Retrieving capturing groups from a match is really simple.

$detail = pattern('(?<capital>[A-Z])')->match('hello there, General Kenobi')->first();
return $detail->get('capital');
'G'
Last updated on