【问题标题】:Passing additional arguments to preg_replace_callback using PHP 5.2.6使用 PHP 5.2.6 将附加参数传递给 preg_replace_callback
【发布时间】:2012-03-03 23:26:18
【问题描述】:

我一直在研究类似的问题,但我仍然不清楚是否有可能和/或使用 PHP 5.2.6 在 preg_replace_callback 中传递其他参数的最佳方式

在这种情况下,我还希望将 foreach 循环中的 $key 传递给 if_replace 函数。

public function output() {
if (!file_exists($this->file)) {
    return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);

foreach ($this->values as $key => $value) {
    $tagToReplace = "[@$key]";
    $output = str_replace($tagToReplace, $value, $output);
    $dynamic = preg_quote($key);
    $pattern = '%\[if @'.$dynamic.'\](.*?)\[/if\]%'; // produces: %\[if @username\](.*?)\[/if\]%
    $output = preg_replace_callback($pattern, array($this, 'if_replace'), $output);
}

return $output;
}



public function if_replace($matches) {

    $matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
    $matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
    return $matches[0];
}

想知道这样的事情是否可行:

class Caller {

public function if_replace($matches) {

    $matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
    $matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
    return $matches[0];
}

}

$instance = new Caller;

$output = preg_replace_callback($pattern, array($instance, 'if_replace'), $output);

【问题讨论】:

标签: php


【解决方案1】:

PHP 5.3 之前

你可以使用辅助类:

class MyCallback {
    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    public function callback($matches) {
        return sprintf('%s-%s', reset($matches), $this->key);
    }
}

$output = 'abca';
$pattern = '/a/';
$key = 'key';
$callback = new MyCallback($key);
$output = preg_replace_callback($pattern, array($callback, 'callback'), $output);
print $output; //prints: a-keybca-key

自 PHP 5.3 起

你可以使用匿名函数:

$output = 'abca';
$pattern = '/a/';
$key = 'key';
$output = preg_replace_callback($pattern, function ($matches) use($key) {
            return sprintf('%s-%s', reset($matches), $key);
        }, $output);
print $output; //prints: a-keybca-key

【讨论】:

  • 谢谢,这正是我所希望的。欣赏示例,它非常清晰,我能够对其进行调整。
  • 读到这里的人:您可能想使用关键字use 而不是这种相对复杂的方法(有关更多信息,请参阅this answer by @Mark Baker
  • @TheSexiestManinJamaica 上面评论中的答案提供了比添加新类等更好、更简单的解决方案。
  • 这个问题是针对 PHP 5.2.6 的,但我已经更新了答案以包含 PHP 5.3 中引入的匿名函数的解决方案,如@Bald 答案。
【解决方案2】:
$pattern = '';
$foo = 'some text';

return preg_replace_callback($pattern, function($match) use($foo)
{
var_dump($foo);

}, $content);

【讨论】:

    【解决方案3】:

    很遗憾,你不能。在 PHP 5.3 中,您可以简单地使用闭包来访问您作为参数传递的变量。

    在您的情况下,有两种可能的解决方案:干净的和肮脏的。

    肮脏的是将参数存储在全局变量中,以便您可以从回调内部访问它们。

    干净的是创建一个传递参数的类,例如通过构造函数。然后你使用array($instance, 'methodName') 作为回调,并在你的方法中通过$this-&gt;whatever 访问参数。

    【讨论】:

    • 感谢这让我朝着正确的方向前进。我根据您的评论更新了问题,我相信我理解您的建议。
    猜你喜欢
    • 2011-12-21
    • 2013-01-09
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2011-07-10
    相关资源
    最近更新 更多