First occurrence
Matching a first occurrence in a string is the most common use-case.
first()
#
About You can get the first occurrence of a pattern in a subject by calling first()
.
- T-Regx
- PHP
If a match is not found in a subject, SubjectNotMatchedException
is thrown. This is done to relieve you from the
brain strain. It's much easier to develop an application and just assume that this
method has to return a value and go on. No more bothers about empty arrays and empty strings, or a possible
null
/false
hiding somewhere.
note
If you would like to control the subject that isn't matched with your pattern though;
you can do it explicitly with findFirst()
(and orReturn()
, orElse()
, orThrow()
).
first()
with callback#
Use You can call an anonymous function for the first matched occurrence. In this example, we'll print the matched text to the standard output.
- T-Regx
- PHP
note
Casting Detail
to string
is the same as calling text()
method.
#
Match detailsWith Detail
, you can gain access to useful information about the matched occurrence.
- T-Regx
- PHP
You can read more extensively about it on Detail
page.
#
Groups in matchRetrieving capturing groups from a match is really simple.
- T-Regx
- PHP
Of course, first()
callback will only be invoked if your pattern matches the subject.
note
You can learn more about groups on Capturing Group page.
note
Even more, you can visit Inline groups and use all()
, first()
, only()
and offsets()
methods on groups.
#
Return valueIt's also possible to return your custom value from within first()
callback. This custom value will be then returned
from first()
function.
- T-Regx
- PHP
#
Variable callbacksYou can call first()
for any valid PHP callable
which accepts one string parameter (or no parameters).
- T-Regx
- PHP
In this example, Detail
will be cast to string, which is the same as calling Detail.text()
method.
note
Of course, strtoupper
(or any other callback) is only invoked if your subject is matched with the pattern.
#
Arbitrary return typesFrom within first()
callback, you can return any value:
- T-Regx
- PHP
The first()
callback accepts all return types, including: numbers, objects, arrays, booleans and null
:
findFirst()
#
This method allows you to explicitly specify how to handle an unmatched subject. Just chain findFirst()
with
one of the following orReturn()
, orElse()
or orThrow()
.
- T-Regx
- PHP
Read on to learn more about findFirst()
.