php7中使用preg_replace_callback替换preg_replace

18-07-24 16:08 字数 102 阅读 3537 已编辑

php7中,preg_replace()不再支持"\e" (PREG_REPLACE_EVAL),需要使用preg_replace_callback()来代替。

比如下面的代码在php7是不行的。

$out = "<?php \n" . '$k = ' . preg_replace("/(\'\\$[^,]+)/e", "stripslashes(trim('\\1','\''));", var_export($t, true)) . ";\n";

需要使用preg_replace_callback函数改造下。

$out = "<?php \n" . '$k = ' . preg_replace_callback("/(\'\\$[^,]+)/", function ($matches) {
                            return stripslashes(trim($matches[0], '\''));
                        },
                            var_export($t, true)) . ";\n";

如果在回调函数中要使用类的方法

class Template {
    function fetch_str($source)
    {
        return preg_replace("/{([^\}\{\n]*)}/e", "\$this->select('\\1');", $source);
    }

    public function select($tag) 
    {
        return stripslashes(trim($tag));
    }
}

则需要改造成下面的形式。

class Template {
    function fetch_str($source)
    {
        return preg_replace_callback("/{([^\}\{\n]*)}/", [$this, 'select'], $source);
    }

    public function select($tag) 
    {
        return stripslashes(trim($tag[1]));
    }
}
2人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论