Skip to main content

Iterating matches

Use forEach() to easily iterate matched occurrences with your callback. You can call forEach() with a callback, that's invoked with Detail.

forEach() is identical to simply iterating the matcher.

$matcher = Pattern::of('\w+')->match('I like trains');
foreach ($matcher as $detail) {
// use detail
}
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.

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,
Last updated on