[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]
我的一些 BB 代码有双标签,删除它的最佳方法是什么?
我已经尝试了一些主要是正则表达式的东西,但老实说,我是正则表达式的新手。
炎炎设计
浏览 169回答 3
3回答
www说
这绝对是可怕的,但它有效。<?php$bb = '[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]';// regex with start, paragraph, and end capture groups$regex = '#(?<start>(\[[a-z]*\])*+)(?<paragraph>.*)(?<end>(\[\/[a-z]*\])*+)#U';// put matches into $matches arraypreg_match_all($regex, $bb, $matches);// get the stuff we need$start = $matches['start'][0]; // string(12) "[i][b][i][b]"$paragraph = implode('', $matches['paragraph']);// now we will grab each tag$regex = '#\[(?<tag>[a-z])\]#';preg_match_all($regex, $start, $matches);$tags = array_unique($matches['tag']);// and build up the new string$newString = '';foreach($tags as $tag) { $newString .= '[' . $tag . ']';}// create the end tags$end = str_replace('[', '[/', $newString);// put it all together$newString .= $paragraph . $end;echo $newString; // [i][b](This is a paragraph with BBcode.)[/i][/b]这给你 [i][b](This is a paragraph with BBcode.)[/i][/b]在此处查看https://3v4l.org/O8UHO
您可以尝试使用正则表达式(可能像/\[.*\]/U)提取所有标签,然后遍历它们,删除所有重复项快速示例:$bb = '[i][b][i][b](This is a paragraph with BBcode.)[/b][/i][/b][/i]';preg_match_all('/(\[.*\])/gU', $bb, $tags);$metTags = [];foreach($tags[0] as $tag) { // tag has not been met, save it if (in_array($tag, $metTags) === false) { $metTags[] = $tag; // tag have been met already } else { // remove it ONCE $bb = preg_replace('#'.preg_quote($tag).'#', '', $bb, 1); }}echo $bb;由于 preg_replace() 的使用,这可能不是最好的解决方案,但仍然做得很好。编辑:添加代码