Php 获取细枝模板文件中使用的所有变量
是否可以获取细枝模板中使用的所有变量 例如:在模板上Php 获取细枝模板文件中使用的所有变量,php,regex,parsing,twig,Php,Regex,Parsing,Twig,是否可以获取细枝模板中使用的所有变量 例如:在模板上 <!DOCTYPE html> <html> <head> <title>My Webpage</title> </head> <body> <ul id="navigation"> {% for item in navigation %} <li
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>
最好是由twig本身来解决哟,老兄,我听说你喜欢twig,所以我写了一个正则表达式,这样你可以在解析时解析: regex
\{(?!%)\s*#以{{开头,后面不跟%,后面跟0或更多空格
((?:(?!\)[^\s])*)#匹配任何没有点或空格的内容
\s*(?)?
PHP
$string='1!'
我的网页
{导航%中的项目的%1}
{%endfor%}
我的网页
{{a_变量}}
';
preg\u match\u all('/\{(?!%)\s*((?:(?!\)[^\s])*)\s*(?@HamZaDzCyberDeV)它在模板内部使用,但不是模板的参数。调用呈现($op\u模板)的人
不关心项
@HamZaDzCyberDeV你在下结论。存在regex
标记并不意味着解决方案必须只基于有限自动机和有限自动机(顺便说一句,解析
是另一个标记,包含的内容足以解决此问题)@HamZa-DzCyberDeV&Anees v:实现一个自定义的细枝节点访问者是可能的:@HamZa-DzCyberDeV:只要有这么好的解析器可用,我就不会使用正则表达式来实现:-)@Anees v:我认为这是唯一的,但如果你了解解析器在通用语言中的实现方式,那也没什么大不了的。我希望我能对第一个短语投两次赞成票)+1就对这个短语投赞成票,哈哈
Array(1=>'navigation',2=>'a_variable')
\{\{(?!%)\s* # Starts with {{ not followed by % followed by 0 or more spaces
((?:(?!\.)[^\s])*) # Match anything without a point or space in it
\s*(?<!%)\}\} # Ends with 0 or more spaces not followed by % ending with }}
| # Or
\{%\s* # Starts with {% followed by 0 or more spaces
(?:\s(?!endfor)(\w+))+ # Match the last word which can not be endfor
\s*%\} # Ends with 0 or more spaces followed by %}
# Flags: i: case insensitive matching | x: Turn on free-spacing mode to ignore whitespace between regex tokens, and allow # comments.
$string = '<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>';
preg_match_all('/\{\{(?!%)\s*((?:(?!\.)[^\s])*)\s*(?<!%)\}\}|\{%\s*(?:\s(?!endfor)(\w+))+\s*%\}/i', $string, $m);
$m = array_map('array_filter', $m); // Remove empty values
array_shift($m); // Remove first index [0]
print_r($m); // Print results