Match offsets
There are several ways to read offsets of your matched occurrences and your capturing groups.
Detail
#
Using If you use Detail
object (like the one passed to first()
, forEach()
or map()
callback) you can just use
offset()
method.
- T-Regx
- PHP
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()
.
offsets()
method#
Using inline Use inline methods to simply return the offsets - when there is no need for using Detail
details or any other operations.
#
ManyIf you only want to get offsets of your matches, use offsets()->all()
.
- T-Regx
- PHP
You can also limit your matches.
- T-Regx
- PHP
#
OneTo only get offset of the first occurrence of a matched pattern, call offsets()->first()
.
- T-Regx
- PHP
As any other first()
method, it throws SubjectNotMatchedException
if the subject isn't matched by your pattern.
#
Group offsetsIn 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.
Detail
#
Using - T-Regx
- PHP
Can also be written as...
offsets()
method#
Using inline - T-Regx
- PHP
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.