Skip to main content

Map occurrences

Mapping works a bit like a combination of all() and forEach(). It returns all matched elements, after they have been iterated (and potentially altered) using map() callback (which accepts Detail details).

Map matched occurrences#

So instead of returning all elements:

pattern("[\w']+")->search("I'm 19 years old")->all();
["I'm", '19', 'years', 'old'] can map them - to any other value, by callback:

pattern("[\w']+")->match("I'm 19 years old")->map(function (Detail $detail) {
return strLen($detail->text());
[3, 2, 5, 3]

Variable callbacks#

You can invoke map() with any valid PHP callable which accepts one string parameter (or no parameters) - just like first().

pattern("[\w']+")->match("I'm 19 years old")->map('strToUpper');
["I'M", "19", "YEARS", "OLD"]

Arbitrary return types#

Again, just like first(), this method can return values of any type, including: objects, arrays, booleans and null.

pattern("[\w']+")->match("I'm 19 years old")->map('str_split');
[ ['I', '\'', 'm'], ['1', '9'], ['y', 'e', 'a', 'r', 's'], ['o', 'l', 'd'] ]


You can just as easily create a flattened map.

pattern("[\w']+")->match("I'm 19 years old")->flatMap('str_split');
['I', '\'', 'm', '1', '9', 'y', 'e', 'a', 'r', 's', 'o', 'l', 'd']

Read more about flatMap() on the next page.

Last updated on