Search code examples
phpregexpreg-replace-callback

Replace and extract matches with regex


How can I get all matches with for example preg_match_all() and also replace the results with an empty string?

I've tried stuff like this:

<?php
$comments   = array();              

$selectors  = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) {
    $comments[] = $match[0];
    return '';
}, $input);
?>

But that doesn't work very well since the $comment variable doesn't seem to be accessable from the anonymous function. I guess I can make global variables, but I really don't want to mess up the namespace like that


Solution

  • This should work:

    <?php
    $comments   = array();              
    
    $selectors  = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
    function ($match) use (&$comments) {  //add the variable $comments to the function scope
        $comments[] = $match[0];
        return '';
    }, $input);
    ?>