使用 PHP 5.2.6 将其他参数传递给preg_replace_callback

php
2022-08-30 19:30:05

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

在本例中,我还希望将$key从 foreach 循环传递到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);

答案 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

答案 2
$pattern = '';
$foo = 'some text';

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

}, $content);

推荐