2

I want to be able to strip all BBCode from a string, except for the [quote] BBCode.

I have the following patterns that could be possible for quotes:

[quote="User"]
[quote=User]
[quote]
Text
[/quote]
[/quote]
[/quote]

This is what I currently use to strip the BBCode that works:

$pattern = '|[[\/\!]*?[^\[\]]*?]|si';
$replace = '';
$quote = preg_replace($pattern, $replace, $tag->content);
4

1 回答 1

2

几乎有一些解决方案

<?php
  function show($s) {
    static $i = 0;
    echo "<pre>************** Option $i ******************* \n" . $s . "</pre>";
    $i++;
  }

  $string = 'A [b]famous group[/b] once sang:
    [quote]Hey you,[/quote]
    [quote mlqksmkmd]No you don\'t have to go[/quote]

    See [url
    http://www.dailymotion.com/video/x9e7ez_pony-pony-run-run-hey-you-official_music]this video[/url] for more.';

  // Option 0
  show($string);

  // Option 1: This will strip all BBcode without ungreedy mode
  show(preg_replace('#\[[^]]*\]#', '', $string));

  // Option 2: This will strip all BBcode with ungreedy mode (Notice the #U at the end of the regex)
  show(preg_replace('#\[.*\]#U', '', $string));

  // Option 3: This will replace all BBcode except [quote] without Ungreedy mode
  show(preg_replace('#\[((?!quote)[^]])*\]#', '', $string));

  // Option 4: This will replace all BBcode except [quote] with Ungreedy mode
  show(preg_replace('#\[((?!quote).)*\]#U', '', $string));

  // Option 5: This will replace all BBcode except [quote] with Ungreedy mode and mutiple lines wrapping
  show(preg_replace('#\[((?!quote).)*\]#sU', '', $string));
?>

所以实际上,我认为这只是选项 3 和 5 之间的选择。

  • [^]]选择每个不是]. 它允许“模拟”非贪婪模式。
  • U正则表达式选项允许我们使用.*而不是[^]]*
  • s正则表达式选项允许匹配多行
  • (?!quote)允许我们在下一个选择中说出与“引用”不匹配的任何内容。它是这样使用的:((?!quote).)*. 请参阅正则表达式以匹配不包含单词的行?了解更多信息。

这个小提琴是一个现场演示。

于 2013-11-09T19:03:25.617 回答