解析 PHP 中的 smarty-like 字符串的参数和值
Parse parameters and values of smarty-like string in PHP
我正在尝试创建类似 smarty 的解析器。对于非常小的部分代码,并且不想实现巨大的类似聪明的解析器。
我想到的是:
(?:([a-zA-Z0-9]+)=(?:([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
在 https://regex101.com/r/l5FI5f/2/ 上看起来不错。每场比赛都是 1 或 2 个条目 + 完整比赛。
当我复制 PHP 代码时,情况看起来不一样...
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 来自哪里...
您需要使用branch reset groups:
(?|([a-zA-Z0-9]+)=(?|([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
^ ^
参见regex demo。
来自参考:
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.
我正在尝试创建类似 smarty 的解析器。对于非常小的部分代码,并且不想实现巨大的类似聪明的解析器。
我想到的是:
(?:([a-zA-Z0-9]+)=(?:([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
在 https://regex101.com/r/l5FI5f/2/ 上看起来不错。每场比赛都是 1 或 2 个条目 + 完整比赛。
当我复制 PHP 代码时,情况看起来不一样...
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 来自哪里...
您需要使用branch reset groups:
(?|([a-zA-Z0-9]+)=(?|([^\v '"]+)|"(.*?)"|'(.*?)')|([a-zA-Z0-9]+))
^ ^
参见regex demo。
来自参考:
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.