我一直在研究类似的问题,但我仍然不太清楚使用 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);
最佳答案
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
关于php - 使用 PHP 5.2.6 将附加参数传递给 preg_replace_callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550769/