2

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.

praine
  • 405
  • 1
  • 3
  • 14

1 Answers1

1

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);
Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
  • Thanks! That did the trick - so simple, yet so hard to find in the documentation. I also found that if I declared the $replaced variable global both inside the class function and inside the anonymous function, it worked - but this probably isn't a good way to do it. – praine May 01 '16 at 08:47
  • 1
    yes global should be used only for extreme needs, glad it helped you ) – Yehia Awad May 01 '16 at 08:56