Question

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

Was it helpful?

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);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top