本文详解如何将原有 preg_replace 的 /e 修饰符迁移至 preg_replace_callback,并通过 use 关键字将上下文变量(如 $this、$template 等)安全注入匿名回调函数,从而正确调用类中已定义的 get_templates_callback 方法。
PHP 7.0 起已彻底移除 preg_replace 的 e(PREG_REPLACE_EVAL)修饰符,原写法:
$template['template_html'] = preg_replace('~(.*?) ~se',
'$this->get_templates_callback(\'\\1\', \'\\2\', $template[\'template_name\'])',
$template['template_html']);不仅语法报错(T_ENCAPSED_AND_WHITESPACE),更因动态执行字符串存在严重安全隐患,必须重构为 preg_replace_callback。
核心在于:preg_replace_callback 的回调函数仅接收一个参数——即 array $matches(含完整匹配及各捕获组),无法直接传入 $this 或 $template['template_name'] 等外部变量。解决方案是使用 匿名函数 + use 闭包绑定:
$template_name = $template['template_name'];
$template['template_html'] = preg_replace_callback(
'~(.*?) ~s', // 移除 'e',保留 's'(DOTALL)
function ($matches) use ($template_name) {
// $matches[0] = 整个匹配字符串(如 ... )
// $matches[1] = 第一组捕获(条件表达式,如 '$x')
// $matches[2] = 第二组捕获(内部代码块,如 'Hello World')
return $this->get_templates_callback($matches[1],
$matches[2], $template_name);
},
$template['template_html']
);⚠️ 注意事项:
✅ 最佳实践总结: