开发者

using preg_match_all for nested brackets

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.


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 *.


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 [^}]+.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜