2013-09-22 41 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是一個現場演示。

相關問題