2013-09-22 40 views
2

我希望能够从字符串中除去所有的BBCode,除了[quote] BBCode。从字符串中除去所有的BBCode,除了[quote]

我有以下的模式,可以为报价可能:

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

这是我目前使用剥离的作品BB代码:

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

使用[PHP的BBCode扩展](http://php.net/bbcode)。 – Gumbo

回答

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).)*。有关更多信息,请参阅Regular expression to match a line that doesn't contain a word?

This fiddle是一个现场演示。

相关问题