【问题标题】:Allow write access to array in PHP preg_replace_callback允许对 PHP preg_replace_callback 中的数组进行写访问
【发布时间】:2016-08-26 02:44:37
【问题描述】:

我正在尝试写入一个在匿名 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);
    }
}

“$replaced”的 var_dump 将其显示为空数组。 preg_replace_callback 循环是公共类函数的一部分,如果这有什么不同的话。

我试过用谷歌搜索这个问题,但没有成功。 非常感谢您对此问题的任何帮助。

【问题讨论】:

  • 你用的是什么php版本?

标签: php regex class scope preg-replace-callback


【解决方案1】:

你快到了: 如果您打算在范围之外重用它,您忘记将引用 &amp; 添加到 $replaced 参数内的 $replaced 变量。

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

【讨论】:

  • 谢谢!这就是诀窍 - 如此简单,但在文档中却很难找到。我还发现,如果我在类函数和匿名函数中都声明了 $replaced 变量 global,它会起作用 - 但这可能不是一个好方法。
  • 是的 global 应该只用于极端需求,很高兴它帮助了你)
猜你喜欢
  • 2014-03-19
  • 1970-01-01
  • 2018-12-31
  • 2023-03-21
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2011-01-27
相关资源
最近更新 更多