gpt4 book ai didi

php - 在较长的文本中使用 php/regex 查找匹配的括号

转载 作者:可可西里 更新时间:2023-10-31 22:46:38 25 4
gpt4 key购买 nike

我已经尝试了很长时间来解决这个问题,但仍然没有找到解决方案。

我正在研究一些简单的格式化方法,我想要一些在括号内包含字符串的标签,标签在括号之前定义。标签也应该能够位于其他括号内。

字符串:

This is some random text, tag1{while this is inside a tag2{tag}}. This is some
other text tag2{also with a tag tag3{inside} of it}.

我现在要做的,就是每一个的内容

tag1{}
tag2{}
tag3{}

我发现其他人也有类似的问题 ( Find matching brackets using regular expression ),但他们的问题更侧重于如何在其他括号内找到匹配的括号,而我的问题是这两个问题,以及在更长的文本中找到多个括号。

最佳答案

如果标签总是平衡的,您可以使用这样的表达式来获取所有标签的内容和名称,包括嵌套标签。

\b(\w+)(?={((?:[^{}]+|{(?2)})*)})

Example :

$str = "This is some random text, tag1{while this is inside a tag2{tag}}. This is some other text tag2{also with a tag  tag3{inside} of it}.";

$re = "/\\b(\\w+)(?={((?:[^{}]+|{(?2)})*)})/";
preg_match_all($re, $str, $m);

echo "* Tag names:\n";
print_r($m[1]);
echo "* Tag content:\n";
print_r($m[2]);

输出:

* Tag names:
Array
(
[0] => tag1
[1] => tag2
[2] => tag2
[3] => tag3
)
* Tag content:
Array
(
[0] => while this is inside a tag2{tag}
[1] => tag
[2] => also with a tag tag3{inside} of it
[3] => inside
)

关于php - 在较长的文本中使用 php/regex 查找匹配的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9126586/

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