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 forEach() or map() callback) you can just use offset() method.

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

Method offset() is UTF-8 safe and returns offsets in characters, not bytes. For bytes, consider using byteOffset() method. Use offset() with multibyte-safe methods like mb_substr(), and byteOffset() with methods like substr().

Using Detail#

$detail = pattern('(?<capital>[A-Z])[a-z]+')->match('my name is John Cena')->first();
return $detail->group('capital')->offset();
11
Last updated on