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.
Matchto a string is the same as calling a
Match details, you can gain access to useful information about the matched occurrence.
Groups in match
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 familiar
offsets()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,
Match 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.
Arbitrary return types
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