【发布时间】: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);
【问题讨论】:
-
回调函数是一个闭包,你可以通过使用传递额外的参数,请在stackoverflow.com/questions/16445991/…查看答案
标签: php