我正在尝试写入一个在匿名preg_replace_callback函数之外初始化的数组。我已经尝试了“use”关键字,并且还声明变量“global”,但似乎都不起作用。
这是我的代码:
$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);
}
}
var_dump“$ replacement”将其显示为空数组。 preg_replace_callback循环是公共类函数的一部分,如果这有任何区别的话。
我试过谷歌搜索这个问题,但没有成功。 非常感谢对这个问题的任何帮助。
答案 0 :(得分:1)
你几乎在那里:
如果您打算在范围之外重复使用,则忘记在&
参数中添加引用$replaced
到use
变量。
$transcript=preg_replace_callback("/(\b".$headword."\b)/", function($m) use($index, &$replaced){
$replaced[$index]=$m[1];
return "<".$index.">";
}, $transcript);