PHP: `preg_match_all_callback`
Published:
There are several PCRE functions available, but today I looked for one that just wasn't there: preg_match_all_callback()
.
Could've maybe used preg_replace_callback()
, but felt wrong since I didn't actually want to do any replacing. I just needed my function to be called for each match.
So I wrote it myself. Noting it here, in case I (or someone else) needs it again.
<?php
/**
* Perform a global regular expression match
* and calls the callback for each match.
*/
function preg_match_all_callback(
string $pattern,
string $subject,
callable $callback)
{
$r = preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach($matches ?? [] as $match)
$callback($match);
return $r;
}
And, in case someone reads this post and knows it actually does exist... and if that someone is you, please do leave a comment!
And, yes, I could've just written those 3 lines where I needed them, but what's the fun in that? And besides, the shorter the code where it counts, the easier what counts is to read.
Usage
preg_match_all_callback('/(\w)\w*/', 'Hello World', 'var_dump');
array (size=2)
0 => string 'Hello' (length=5)
1 => string 'H' (length=1)
array (size=2)
0 => string 'World' (length=5)
1 => string 'W' (length=1)