我正在使用preg_mat替换模板中的if语句。我一直试图从preg_match_all获取匹配并从匹配中获得结果并使用preg_replace,但我得到偏移错误。
非常感谢对语法的任何帮助。同样好奇是否有更好的方法来解决这个问题。
代码示例:
public function output() {
$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\]%
if ($value == '') {
$output = preg_replace($pattern, "", $output);
} else {
preg_match_all($pattern, $output, $if_match);
$output = preg_replace("%\[if @".$dynamic."\]%", "", $if_match[0][0]);
$output = preg_replace("%\[/if]%", "", $if_match[0][0]);
}
模板除外:
[if @username] <p>A statement goes here and this is [@username]</p> [/if]
[if @sample] <p>Another statement goes here</p> [/if]
控制器摘录:
$layout->set("username", "My Name");
$layout->set("sample", "");
答案 0 :(得分:0)
使用回调然后在$ matches上运行preg_replace解决了问题:
public function output() {
$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\]%
if ($value == '') {
$output = preg_replace($pattern, "", $output);
} else {
$callback = new MyCallback($key, $value);
$output = preg_replace_callback($pattern, array($callback, 'callback'), $output);
}
}
return $output;
}
}
class MyCallback {
private $key;
private $value;
function __construct($key, $value) {
$this->key = $key;
$this->value = $value;
}
public function callback($matches) {
$matches[1] = preg_replace("%\[if @".$this->key."\]%", "", $matches[1]);
$matches[1] = preg_replace("%\[/if]%", "", $matches[1]);
return $matches[1];
}
}