【问题标题】:Codeigniter preg_replace_callbackCodeigniter preg_replace_callback
【发布时间】:2010-02-11 01:26:32
【问题描述】:

我希望preg_replace_callback 使用来自 CodeIgniter 的库函数作为其回调。我目前不成功的尝试如下:

$content = preg_replace_callback('/href="(\S+)"/i',
    '$this->util->url_to_absolute("http://www.google.com","$matches[0]")',
    $content);

但我没有任何成功。我试过使用create_function,但我也无法让它工作。任何帮助将不胜感激。

【问题讨论】:

    标签: php codeigniter callback


    【解决方案1】:

    它看起来更像:

    $content = preg_replace_callback(
        '/href="(\S+)"/i',
        create_function(
            '$matches',
            'return $this->util->url_to_absolute("http://www.google.com","$matches[1]")'),
        $content);
    

    但问题是 $this 引用在回调范围内不可用,因此您可能需要在回调内实例化它或在您自己的类中使用回调,例如:

    class fred {
    
        function callback1($matches) {
           return $this->util->url_to_absolute("http://www.google.com","$matches[1]");
        }
    
        function dostuff($content) {
            $content = preg_replace_callback(
                '/href="(\S+)"/i',
                array($this, 'callback1'),
                $content);
            return $content;
        }
    }
    

    假设类 fred 和 dostuff 是您当前尝试从中调用它的类和方法,

    【讨论】:

      【解决方案2】:

      从 php 5.3 开始

      $that = $this;
      $content = preg_replace_callback($patt, function($matches) use ($that) {
          return $that->util->url_to_absolute("http://www.google.com", $matches[1]);
      }, $content);
      
      //or
      $that = $this->util;
      $content = preg_replace_callback($patt, function($matches) use ($that) {
          return $that->url_to_absolute("http://www.google.com", $matches[1]);
      }, $content);
      
      //or
      $callback = array($this->util, 'url_to_absolute');
      $content = preg_replace_callback($patt, function($matches) use ($callback) {
          return call_user_func($callback, "http://www.google.com", $matches[1]);
      }, $content);
      

      【讨论】:

      • 我在看那个,但我们的系统在 5.2.6 上运行 :(.
      猜你喜欢
      • 2014-01-28
      • 2017-06-02
      • 2016-02-07
      • 1970-01-01
      • 2014-04-27
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      相关资源
      最近更新 更多