Skip to main content

Match offsets

There are several ways to read offsets of your matched occurrences and your capturing groups.

Using Detail#

If you use Detail object (like the one passed to first(), forEach() or map() callback) you can just use offset() method.

pattern('\d+')->match('I was born in 1996')->first(function (Detail $detail) {
return 'Match was found at ' . $detail->offset();
});
'Match was found at 14'
note

Method offset() is UTF-8 safe and returns offsets in characters, not bytes. For bytes, consider using byteOffset() method.

note

Use offset() with multibyte-safe methods like mb_substr(), and byteOffset() with methods like substr().

Using inline offsets() method#

Use inline methods to simply return the offsets - when there is no need for using Detail details or any other operations.

Many#

If you only want to get offsets of your matches, use offsets()->all().

pattern('[0-9]+')->match("I'm 19 years old. I was born in 1999, May 12")->offsets()->all();
[4, 32, 42]

You can also limit your matches.

pattern('[0-9]+')->match("I'm 19 years old. I was born in 1999, May 12")->offsets()->only(2);
[4, 32]

One#

To only get offset of the first occurrence of a matched pattern, call offsets()->first().

pattern('\d+')->match("I was born in 1999")->offsets()->first();
14

As any other first() method, it throws SubjectNotMatchedException if the subject isn't matched by your pattern.

Group offsets#

In a similar manner, you can get offsets of your capturing groups, either using Detail or an inline method.

These two snippets below are equal to each other.

Using Detail#

pattern('(?<capital>[A-Z])[a-z]+')->match('my name is John Cena')->first(function (Detail $detail) {
return $detail->group('capital')->offset();
});
11

Can also be written as...

Using inline offsets() method#

pattern('(?<capital>[A-Z])[a-z]+')->match('my name is John Cena')->group('capital')->offsets()->first();
11

Both offsets()->first() and group()->offsets()->first() throw SubjectNotMatchedException if the subject isn't matched by your pattern.

Also, both Detail.group() details and inline match()->group()->offsets() throw GroupNotMatchedException, when used with an unmatched group.

Last updated on