简体   繁体   English

PHP中是否有一个(递归的)PCRE正则表达式来标记标签

[英]Is there a (recursive) PCRE regexp in PHP to denest tags

I have an initial string with miscellaneous texts between tags in it, and the string can contain nested tags. 我有一个初始字符串,其中的标签之间包含其他文本,并且该字符串可以包含嵌套标签。 I wish to "de-nest" the string according to the following rules : 1) the final string does not differ from the initial one except by adding or deleting some tags. 我希望根据以下规则“删除”字符串:1)最终字符串与初始字符串没有区别,只是添加或删除了一些标签。 2) In the final string, every piece of text is enclosed by the nearest pair of tags that enclosed it in the original string. 2)在最后一个字符串中,每段文本都由将其括在原始字符串中的最接近的一对标记包围。 If there are several equally near pairs, the result in unspecified(but 3) no piece of text gets attributed new tags in the final string). 如果有几个相等的近对,则结果未指定(但为3),则没有文本在最终字符串中归属新的标记)。

Thus, 从而,

[a]text1[/a]text2[b]text3[c]text4[/c]text5[/b]
[e]text6[f]text7[/e]text8[/f]

should become 应该成为

[a]text1[/a]text2[b]text3[/b][c]text4[/c][b]text5[/b]
[e]text6[/e]...[f]text8[/f]

where might be any of text7 , [e]text7[/e] or [f]text7[/f] . 其中可以是text7[e]text7[/e][f]text7[/f]

Is there a regexp (for example, a recursive PCRE regexp in PHP) that does this ? 是否有这样做的正则表达式(例如,PHP中的递归PCRE正则表达式)?

Method 方法

Execute 3 replacements: 执行3次替换:

  1. Search for a closing tag followed by another closing tag ==> insert an opening tag for the second. 搜索结束标记,然后搜索另一个结束标记==>为第二个插入开始标记。 Example: 例:

     [/b]text[/c] ==> [/b][c]text[/c] 
  2. Search for an opening tag followed by a tag which is not the closing tag corresponding to the one it has just found ==> insert the closing tag. 搜索一个开始标签,后跟一个标签,该标签不是与其刚刚找到的标签相对应的结束标签==>插入结束标签。 Example: 例:

     [a]text[b] ==> [a]text[/a][b] [a]text[/b] ==> [a]text[/a][/b] 
  3. (A fix to 2). (修正为2)。 Search for 2 consecutive closing tags ==> remove the second. 搜索2个连续的结束标签==>删除第二个。 Example: 例:

     [a]text[/a][/b] ==> [a]text[/a] 

Code

$patterns = array ('#(\[/\w++])([^[]++\[/(\w++)])#',
                   '#\[(\w++)][^[]*+(?!\[/\1)#',
                   '#(\[/(\w++)])\[/\w++]#');
$replace = array ('\1[\3]\2', 
                  '\0[/\1]',
                  '\1');

$string = "[a]text1[/a]text2[b]text3[c]text4[/c]text5[/b]\n[e]text6[f]text7[/e]text8[/f]";

$result = preg_replace($patterns, $replace, $string);

Output 产量

[a]text1[/a]text2[b]text3[/b][c]text4[/c][b]text5[/b]
[e]text6[/e][f]text7[/f][f]text8[/f]

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

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