php 模板引擎,preg_replace
php templating engine, preg_replace
嘿,我正在尝试制作模板引擎,但是 运行 遇到了 if 语句的问题
$this->template = preg_replace('~@if\((.*?)\)~', '?php if(): ?', $this->template);
$this->template = preg_replace('~@elseif\((.*?)\)~', '<?php elseif(): ?>', $this->template);
$this->template = preg_replace('~@else~', '<?php else: ?>', $this->template);
$this->template = preg_replace('~@endif~', '?php endif; ?', $this->template);
发生的情况是,如果我尝试用字符串中的其他括号替换字符串,preg_replace 会第一个出现,而不是
上的右侧
例子
@if(!isset($active)) Show @endif
变成
<?php if(!isset($active): ?>) Show @endif
为了描述括号中包含的内容并最终在其中嵌套括号,模式是("if" 模式的示例):
~@if\(([^()]*+(?:\((?-1)\)[^()]*)*+)\)~
(?-1)
代表最后打开的捕获组中的子模式。由于它在捕获组本身中,因此您获得了递归。 (请注意,您也可以使用 (?1)
的捕获组编号调用子模式,而不是像示例中那样以相对方式调用,但是当模式包含多个时,相对方式更有用捕获组。)
该模式使用所有格量词 *+
(禁止回溯)在字符串格式不正确时更快地失败。
嘿,我正在尝试制作模板引擎,但是 运行 遇到了 if 语句的问题
$this->template = preg_replace('~@if\((.*?)\)~', '?php if(): ?', $this->template);
$this->template = preg_replace('~@elseif\((.*?)\)~', '<?php elseif(): ?>', $this->template);
$this->template = preg_replace('~@else~', '<?php else: ?>', $this->template);
$this->template = preg_replace('~@endif~', '?php endif; ?', $this->template);
发生的情况是,如果我尝试用字符串中的其他括号替换字符串,preg_replace 会第一个出现,而不是
上的右侧例子
@if(!isset($active)) Show @endif
变成
<?php if(!isset($active): ?>) Show @endif
为了描述括号中包含的内容并最终在其中嵌套括号,模式是("if" 模式的示例):
~@if\(([^()]*+(?:\((?-1)\)[^()]*)*+)\)~
(?-1)
代表最后打开的捕获组中的子模式。由于它在捕获组本身中,因此您获得了递归。 (请注意,您也可以使用 (?1)
的捕获组编号调用子模式,而不是像示例中那样以相对方式调用,但是当模式包含多个时,相对方式更有用捕获组。)
该模式使用所有格量词 *+
(禁止回溯)在字符串格式不正确时更快地失败。