Matching a first occurrence in a string is the most common use-case.
You can get the first occurrence of a pattern in a subject by calling
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
false hiding somewhere.
first() with callback#
You can call an anonymous function for the first matched occurrence. In this example, we'll print the matched text to the standard output.
string is the same as calling
Detail, you can gain access to useful information about the matched occurrence.
You can read more extensively about it on
Retrieving capturing groups from a match is really simple.
first() callback will only be invoked if your pattern matches the subject.
You can learn more about groups on Capturing Group page.
Even more, you can visit Inline groups and use
methods on groups.
It's also possible to return your custom value from within
first() callback. This custom value will be then returned
You can call
first() for any valid PHP
callable which accepts one string parameter (or no parameters).
In this example,
Detail will be cast to string, which is the same as calling
strtoupper (or any other callback) is only invoked if your subject is matched with the pattern.
first() callback, you can return any value:
first() callback accepts all return types, including: numbers, objects, arrays, booleans and
Read on to learn more about