这就是我现在得到的:
/{% if(.+?) %}(.*?){% endif %}/gusi
它可以捕获多个if语句等。
IMG:http://image.xesau.eu/2015-02-07_23-22-11.png
但是当我进行嵌套时,如果中的if,它会在{%endif%}的第一次出现时停止
IMG:http://image.xesau.eu/2015-02-08_09-29-43.png
有没有办法捕获与{%if…%}语句一样多的{%endif%}个语句?如果有,如何捕获?
不要使用regexen,使用现有的Twig解析器。以下是我编写的提取器的示例,该提取器解析自定义标签并提取它们:https://github.com/deceze/Twig-extensions/tree/master/lib/Twig/Extensions/Extension/Gettext
lexer的工作是将Twig源代码转换为对象;如果你需要连接到这个过程中,你可以扩展它:
class My_Twig_Lexer extends Twig_Lexer {
...
/**
* Overrides lexComment by saving comment tokens into $this->commentTokens
* instead of just ignoring them.
*/
protected function lexComment() {
if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
}
$value = substr($this->code, $this->cursor, $match[0][1] - $this->cursor);
$token = new Twig_Extensions_Extension_Gettext_Token(Twig_Extensions_Extension_Gettext_Token::COMMENT, $value, $this->lineno);
$this->commentTokens[] = $token;
$this->moveCursor($value . $match[0][0]);
}
...
}
通常Twig注释节点被Twig丢弃,这个lexer保存它们。
然而,您主要关心的是使用解析器:
$twig = new Twig_Environment(new Twig_Loader_String);
$lexer = new My_Twig_Lexer($twig);
$parser = new Twig_Parser($twig);
$source = file_get_contents($file);
$tokens = $lexer->tokenize($source);
$node = $parser->parse($tokens);
processNode($node);
这里的$node
是以面向对象的方式表示Twig源的节点树的根节点,所有这些都已经正确解析。您只需要处理这个树,而不必担心用于生成它的确切语法:
processNode(Twig_NodeInterface $node) {
switch (true) {
case $node instanceof Twig_Node_Expression_Function :
processFunctionNode($node);
break;
case $node instanceof Twig_Node_Expression_Filter :
processFilterNode($node);
break;
}
foreach ($node as $child) {
if ($child instanceof Twig_NodeInterface) {
processNode($child);
}
}
}
只需遍历它,直到找到要查找的节点类型并获取其信息。玩一玩。这个示例代码可能有点过时,也可能没有过时,无论如何你都必须深入研究Twig解析器的源代码才能理解它。
将模式更改为递归模式几乎是微不足道的:
{% if(.+?) %}((?>(?R)|.)*?){% endif %}
工作示例:https://regex101.com/r/gX8rM0/1
然而,这将是一个坏主意:模式缺少许多情况,这些情况实际上是解析器中的错误。只有几个常见的例子:
评论:
{% if aaa %} 123 <!-- {% endif %} --> {% endif %}
字符串文字:
{% if aaa %}a = "{% endif %}"{% endif %} {% if $x == "{% %}" %}...{% endif %}
转义字符(您确实需要转义字符,对吗?):
<p>To start a condition, use <code>'{% if aaa %}</code></p>
无效输入:
如果解析器能够相对较好地处理无效输入,并指向错误的正确位置,那就太好了。