gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:47:54 24 4
gpt4 key购买 nike

我有一个字符串,其中包含几个我想删除的大括号中的句子。这并不难做到(正如我现在所知道的那样),但真正的问题是它是多层次的,我想要剥离的只是顶层括号并保持里面的一切完好无损。它看起来像这样:

{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}.}

我想创建一个包含这四个条目的数组:

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

我尝试了两种方法,一种是 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>";
}

另一个使用的是 preg_match_all,它非常好,直到我意识到我有那些多级括号:

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

提前致谢! :)

最佳答案

你可以像这样使用递归表达式:

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

期望的结果将在第一个捕获组中。

用法,类似于:

preg_match_all('/{((?:[^{}]++|(?R))*+)}/', $str, $matches);
$result = $matches[1];

关于PHP、正则表达式和多级大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11024495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com