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

标签 php regex

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

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

字符串:

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/

相关文章:

php - 自动触发查询并在php中发送邮件

mysql - 选择以 5 个数字字符开头的所有电子邮件地址(正则表达式)

PHP - 检测字符串之间的空格

php - 每次 PHPUnit 测试后换行

php - 通过或使用 PHP 的 MySQL GROUP?

php - mysql:使用另一个表的数据对表行进行排序

javascript - 从pdf文件中读取注释

javascript - 正则表达式,搜索多个换行符

Python,正则表达式 : find and replace all instances of "yyyy" except when in front of a period

java - 如何使用正则表达式查找两个\n 之间的子字符串?