使用PHP5.2.6将附加参数传递给preg_replace_回调
我一直在研究类似的问题,但我仍然不清楚使用PHP5.2.6在preg_replace_回调中传递附加参数是否可能和/或最好 在本例中,我还希望将$key从foreach循环传递到if_replace函数使用PHP5.2.6将附加参数传递给preg_replace_回调,php,Php,我一直在研究类似的问题,但我仍然不清楚使用PHP5.2.6在preg_replace_回调中传递附加参数是否可能和/或最好 在本例中,我还希望将$key从foreach循环传递到if_replace函数 public function output() { if (!file_exists($this->file)) { return "Error loading template file ($this->file).<br />"; } $output = f
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];
}
不幸的是你不能。在PHP5.3中,您可以简单地使用闭包来访问作为参数传递的变量 在您的情况下,有两种可能的解决方案:干净的和脏的 脏的是将参数存储在全局变量中,以便您可以从回调内部访问它们
干净的方法是创建一个类,在其中传递参数,例如通过构造函数。然后使用
array($instance,'methodName')
作为回调函数,只需通过$this->方法内部的任何内容访问参数。PHP5.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
,而不是这种相对复杂的方法(有关更多信息,请参阅)以上@TheSexiestManinJamaica评论中的答案为这个问题提供了一个比添加新类等更好、更简单的解决方案。这个问题是针对PHP5.2.6的,但我已经更新了答案,包括PHP5.3中引入的匿名函数的解决方案,如@Bald answer。Acallback函数是一个闭包,您可以通过use传递额外的参数,请在
$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
$pattern = '';
$foo = 'some text';
return preg_replace_callback($pattern, function($match) use($foo)
{
var_dump($foo);
}, $content);