所以我得到了这个:
$output = "bla bla {_here I am (lots of things) can happen here! it's ok} bla bla";
@preg_match_all('/.*{_([^}]*)}/',$output, $conditions);
结果如预期,直到我们有多个括号。 我想获取字符串的内容:
$output = "bla bla {_here I am (lots of things) {conflict} can happen here! it's ok} bla bla"
@preg_match_all('/.*{_([^}]*)}/',$output, $conditions);
我希望获得彼此对应的括号内容 结果应该是这样的:
1. {_here I am (lots of things) {conflict} can happen here! it's ok}
2. {conflict}
答案 0 :(得分:3)
通常,正则表达式不是解析递归模式的特别好的选择,我建议不要使用它们。
如果您知道您的输入只能有两个级别的括号,那么这样的模式就足够了:
/{_[^{}]*(?:({[^{}]*})[^{}]*)*}/
例如:
$output = "bla bla {_here I am (lots of things) {conflict} can happen here! it's ok} bla bla";
preg_match('/{_[^{}]*(?:({[^{}]*})[^{}]*)*}/',$output, $conditions);
但是,PHP确实有支持recursive patterns的扩展。例如:
$output = "bla bla {_here I am (lots of things) {conflict} can happen here! it's ok} bla bla";
preg_match('/{(?:[^{}]*|((?R)))*}/',$output, $conditions);
以上两个样本都会产生:
Array
(
[0] => {_here I am (lots of things) {conflict} can happen here! it's ok}
[1] => {conflict}
)
答案 1 :(得分:1)
如果您有多个级别的嵌套,则可以使用此模式:
preg_match('~(?=({(?>[^{}]++|(?1))*}))/',$output, $conditions);
这种使用递归的模式((?1)
是捕获组1的别名),因为它嵌入在先行断言中,所以会给你所有重叠的结果。