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 Match details).

Map matched occurrences

So instead of returning all elements:

  • T-Regx
  • PHP
pattern("[\w']+")->match("I'm 19 years old")->all();
["I'm", '19', 'years', 'old']

...you can map them - to any other value, by callback:

  • T-Regx
  • PHP
pattern("[\w']+")->match("I'm 19 years old")->map(function (Match $match) {
return strlen($match->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().

  • T-Regx
  • PHP
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.

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

flatMap()

You can just as easily create a flattened map.

  • T-Regx
  • PHP
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