如何使用预先存在的函数为 preg_replace_callback 的回调函数正确传递参数?

How to pass the parameters properly for a callback function for preg_replace_callback using a preexisting function?

我收到此错误:解析错误:语法错误,意外的“”(T_ENCAPSED_AND_WHITESPACE),期望标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING).........第 2 行的 eval() 代码 自从从正则表达式中删除 e ~?)(?( .?)~se 如下一行所示,因为它已被弃用。

$template['template_html'] = preg_replace('~<IF (.*?)(?<!\-)>(.*?)</IF>~se', '$this->get_templates_callback(\'\1\', \'\2\', $template[\'template_name\'])', $template['template_html']);

我知道我需要使用 preg_replace_callback() 并使用匿名函数重写,但是我 运行 遇到重写它的麻烦,因为 $this->get_templates_callback() 需要也被调用和执行。

    function get_templates_callback($condition, $code, $piece)
{
    $macro_id = isset($this->macro[$piece]) ? count($this->macro[$piece]) : 0;
    $this->macro[$piece][$macro_id] = '$macro_replace[' . $macro_id . '] = ((' . $condition . ') ? "' . $code . '" : ""); ';
    return '{' . chr(36) . 'macro_replace[' . $macro_id . ']}';
}

我应该如何正确地将参数传递给这个函数?

您可以使用 use statement 来传递额外的参数。

function (array $matches) use ($condition, $code, $piece)
{
}