Match offsets

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

Using Match details

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

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

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

Use offset() with 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 Match details or any other operations.

Many

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

  • T-Regx
  • PHP
return pattern('[0-9]+')->match("I'm 19 years old. I was born in 1999, on May 12")->offsets()->all();
[4, 32, 45]

You can also limit your matches.

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

One

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

  • T-Regx
  • PHP
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 Match details or an inline method.

These two snippets below are equal to each other.

Using Match details

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

Can also be written as...

Using inline offsets() method

  • T-Regx
  • PHP
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 Match.group() details and inline match()->group()->offsets() throw GroupNotMatchedException, when used with an unmatched group.

Last updated on