Search code examples
phpregexclassscopepreg-replace-callback

Allow write access to array in PHP preg_replace_callback


I'm trying to write to an array which was initialized outside an anonymous preg_replace_callback function. I've tried the "use" keyword, and also declaring the variable "global", but neither seem to work.

Here is my code:

$headwords=array_keys($dict);
$replaced=array();
// Scan text

foreach($headwords as $index=>$headword){
    if(preg_match("/\b".$headword."\b/", $transcript)){
        $transcript=preg_replace_callback("/(\b".$headword."\b)/", function($m) use($index, $replaced){
            $replaced[$index]=$m[1];
            return "<".$index.">";
        }, $transcript);
    }
}

A var_dump of "$replaced" shows it as an empty array. The preg_replace_callback loop is part of a public class function, if that makes any difference.

I've tried Googling this issue but with no success. Very grateful for any help with this problem.


Solution

  • You're almost there: you forget to add the reference & to $replaced variable inside use parameter if you are planning to reuse it outside the scope.

       $transcript=preg_replace_callback("/(\b".$headword."\b)/", function($m) use($index, &$replaced){
            $replaced[$index]=$m[1];
            return "<".$index.">";
        }, $transcript);