使用 preg_match_all 进行嵌套括号
我有一个像这样的字符串:
This is a {{text}} for {{testing}} PHP {{regular expression}}
我使用以下模式来获取包含 {{text}} 、 {{testing}} 的数组, {{正则表达式}}
/\{\{.+\}\}/
但它返回一个只有 1 个元素的数组:
"{{text}} for {{testing}} php {{正则表达式}}"
也尝试了这个:
/\{\{(?R)|.+\}\}/
但我得到了相同的结果。
这个模式有什么问题吗?
谢谢。
I have a string like this:
This is a {{text}} for {{testing}} PHP {{regular expression}}
I use the following pattern to get an array containing {{text}} , {{testing}} , {{regular expression}}
/\{\{.+\}\}/
But it returns an array with only 1 element:
"{{text}} for {{testing}} php {{regular expression}}"
Also tried this one:
/\{\{(?R)|.+\}\}/
But I get the same result.
What's wrong with this pattern?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用
/\{\{.+?\}\}/
,注意 ?,原来是贪婪的,这意味着它将匹配尽可能多的字符,如果你有 .+这意味着将从第一个 { 到最后一个 }。+?
、*?
是+
和*
的非贪婪版本。Try using
/\{\{.+?\}\}/
, notice the ?, the original is greedy, that means it will match as many characters as it can, and if you have .+ it means it will go from the first { to the last }.The
+?
,*?
are the non-greedy versions of+
and*
.我认为更快的解决方案是正则表达式
/\{\{([^}]+)\}\}/
,因为非贪婪量词逐字母获取,直到到达右括号,而此正则表达式第一次尝试就吃掉右括号内的所有东西。另外编辑
,我认为OP希望使用匹配的结果,因此在
[^}]+
周围添加了匹配的括号。I think faster solution would be the regex
/\{\{([^}]+)\}\}/
, because non-greedy quantifier gets letter by letter until it reach right bracket while this regex eats everything up to right bracket on first try.EDIT
additionally, I think the OP want to work with matched result, so added matching parentheses around
[^}]+
.