加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 有没有办法在preg_replace_callback回调函数中传递另一个

发布时间:2020-12-13 16:33:46 所属栏目:PHP教程 来源:网络整理
导读:嗯,我真的很希望我的英文很好地解释我需要什么. 让我们来看看这个例子(这只是一个例子!)的代码: class Something(){ public function Lower($string){ return strtolower($string); }}class Foo{ public $something; public $reg; public $string; public
嗯,我真的很希望我的英文很好地解释我需要什么.

让我们来看看这个例子(这只是一个例子!)的代码:

class Something(){
    public function Lower($string){
        return strtolower($string);
    }
}
class Foo{
    public $something;
    public $reg;
    public $string;
    public function __construct($reg,$string,$something){
        $this->something = $something;
        $this->reg = $reg;
        $this->string = $string;
    }
    public function Replace(){
        return preg_replace_callback($this->reg,'Foo::Bar',$this->string);
    }
    public static function Bar($matches){
        /*
        * [...]
        * do something with $matches and create the $output variable
        * [...]
        */

        /*
        * I know is really useless in this example,but i need to have an istance to an object here
        * (in this example,the Something object,but can be something else!)
        */
        return $this->something->Lower($output);
    }
}
$s = new Something();
$foo = new Foo($myregexp,$mystring,$s);
$content = $foo->Replace();

所以,php手册说,在preg_replace_callback()中使用类方法作为回调,该方法必须是抽象的.

我需要在回调函数中传递一个previuosly已初始化的对象(在该示例中为Something类的一个实例)的实例.

我尝试使用call_user_func(),但没有工作(因为我以这种方式我错过了match参数).

有没有办法做到这一点,还是让我分开进程(在preg_match_all之前,为每个匹配检索替换值,然后是一个简单的preg_replace)?

编辑:作为旁注,在tom haigh答案之前,我使用这个工作(在这个例子中,这是替换方法):

$has_dynamic = preg_match_all($this->reg,$this->string,$dynamic);
if($has_dynamic){
    /*
    * The 'usefull' subset of my regexp is the third,so $dynamic[2]
    */
    foreach($dynamic[2] AS $key => $value){
        $dynamic['replaces'][$key] = $this->Bar($value);
    }
    /*
    * ..but i need to replace the complete subset,so $dynamic[0]
    */
    return str_replace($dynamic[0],$dynamic['replaces'],$this->string);
}else{
    return $this->string;
}

希望可以帮助某人.

很难将参数传递给回调,而不是这样:
return preg_replace_callback($this->reg,$this->string);

您可以使Bar()不是静态的,并使用:

return preg_replace_callback($this->reg,array($this,'Bar'),$this->string);

那么回调函数就可以看到$this了

请参阅Pseudo-types and variables中的“回调”

另外在PHP> = 5.3中,您可以使用anonymous functions/closures将其他数据传递给回调函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读