解析PHP中类似smarty的字符串的参数和值 [英] Parse parameters and values of smarty-like string in PHP
问题描述
我正在尝试创建类似 smarty 的类似解析器.对于非常小的代码部分,并且不想实现巨大的类似 smarty 的解析器.
I'm trying to create simmiliar parser like smarty. For very small parts of code, and don't want to implement huge smarty-like parser.
我想到的是:(?:([a-zA-Z0-9]+)=(?:([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
在 https://regex101.com/r/l5FI5f/2/ 上看起来不错.每场比赛都是 1 或 2 个条目 + 完全匹配.
On https://regex101.com/r/l5FI5f/2/ it looks fine. Every match is either 1 or 2 entries + full match.
当我复制 PHP 代码时,事情看起来不一样了...
When I copy PHP code, things look different...
array (size=5)
0 => string 'xddss='asdasda'' (length=15)
1 => string 'xddss' (length=5)
2 => string '' (length=0)
3 => string '' (length=0)
4 => string 'asdasda' (length=7)
不确定索引 2 和 3 来自哪里...
Not sure where index 2 and 3 come from...
推荐答案
您需要使用分支重置组:
(?|([a-zA-Z0-9]+)=(?|([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
^ ^
请参阅正则表达式演示.
来自参考:
Alternatives 共享相同的捕获组.语法是 (?|regex)
其中 (?|
打开组,regex 是任何正则表达式.如果你不在分支内使用任何交替或捕获组重置组,那么它的特殊功能就不会发挥作用.它然后充当 non- 捕获组.
Alternatives inside a branch reset group share the same capturing groups. The syntax is
(?|regex)
where(?|
opens the group and regex is any regular expression. If you don't use any alternation or capturing groups inside the branch reset group, then its special function doesn't come into play. It then acts as a non-capturing group.
这篇关于解析PHP中类似smarty的字符串的参数和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!