Iterate matches (For each)

Use forEach() to easily iterate matched occurrences with your callback. You can call forEach() with a callback, that's invoked with Detail details just like first() and findFirst().

pattern('\w+')->match('Apples are cool')->forEach(function (Detail $match) {
echo "I matched $match, ";
});
I matched Apples, I matched are, I matched cool,

Using Detail you can get detailed information such as offset(), index() etc.

note

forEach() accepts Detail details, but Detail can be cast to (string).

Vanilla PHP foreach#

You can also use the result of pattern()->match() directly in PHP foreach loop.

foreach (pattern('\w+')->match('Apples are cool') as $match) {
echo "I matched " . $match->text() . ", ";
};
I matched Apples, I matched are, I matched cool,

Other iterable entities#

In the further chapters you will learn about inline offsets(), group(string|int) and asInt() methods in detail, but for now, you only need to know that all of those entities are iterable with PHP foreach.

foreach (pattern('\d+')->match('127.0.0.1')->asInt() as $digit) {
return $digit; // 127
}
127

or

foreach (pattern('(\d+)')->match('127.0.0.1')->group(1) as $group) {
return $group->text(); // '127'
}
'127'

Of course, if you call ->all() on any of the given entities above you will receive an array, which is of course also iterable by PHP foreach.

foreach (pattern('\d+')->match('127.0.0.1')->all() as $text) {
return $text; // '127'
}
'127'

Although, instead of all() it's possible to chain the entities with one of the more high-level T-Regx methods, such as: forEach()/map()/flatMap() etc.

Last updated on