简体   繁体   English

PHP,正则表达式和多级大括号

[英]PHP, regex and multi-level curly brackets

I've got a string which consists of few sentences which are in curly brackets that I want to remove. 我有一个字符串,其中包含几个句子,这些句子都是我要删除的大括号。 That would be not that hard to do (as I know now.), but the real trouble is it's multilevel and all I want to strip is the top level brackets and leave everything inside intact. 这不是那么难(我现在知道了。),但真正的麻烦是它是多层次的,我想剥离的是顶级括号,并将所有内容保持完整。 It looks something like this: 它看起来像这样:

{Super duper {extra} text.} {Which I'm really {starting to} hate!} {But I {won't give up} so {easy}!} {Especially when someone is {gonna help me}.}

I want to create an array that would consist of those four entries: 我想创建一个由这四个条目组成的数组:

Super duper {extra} text.
Which I'm really {starting to} hate!
But I {won't give up} so {easy}!
Especially when someone is {gonna help me}.

I have tried two ways, one was preg_split which didn't do much good: 我尝试了两种方法,一种是preg_split,它没有做太多好处:

$key = preg_split('/([!?.]{1,3}\} \{)/',$key, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();

for ($i=0, $n=count($key)-1; $i<$n; $i+=2) {
$sentences[] = $key[$i].$key[$i+1]."<br><br>";
}

Another one was using preg_match_all which was quite good until I realized I had those brackets multilevel: 另一个是使用preg_match_all这是非常好的,直到我意识到我有这些括号多级:

$matches = array();
$key = preg_match_all('/\{[^}]+\}/', $key, $matches);
$key = $matches[0];

Thanks in advance! 提前致谢! :) :)

You can use a recursive expression like this: 您可以使用这样的递归表达式:

/{((?:[^{}]++|(?R))*+)}/

The desired results will be in the first capturing group. 期望的结果将在第一个捕获组中。

Usage, something like: 用法,例如:

preg_match_all('/{((?:[^{}]++|(?R))*+)}/', $str, $matches);
$result = $matches[1];
$x="foo {bar {baz}} whee";
$re="/(^[^{]*){(.*)}([^}]*)$/";
print preg_replace($re, "\\1\\2\\3", $x) . "\n";'

returns: 收益:

foo bar {baz} whee

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM