tags:

views:

43

answers:

2

How to get ride of all BBcodes in a string but keep the content?

Example:

[B]This is bold[/B] and This is [color=#FFCCCC]colored[/color]

Will be :

This is bold and This is colored

+4  A: 

I suppose you could just use a regular expression and the preg_replace function, to replace everything that's between [ and ] by an empty string :

$str = '[B]This is bold[/B] and This is [color=#FFCCCC]colored[/color]';
echo preg_replace('#\[[^\]]+\]#', '', $str);

Will display :

This is bold and This is colored


Here, the pattern I used is matching :

  • a [ character : \[
  • Anything that's not a ] character : [^\]]
    • One or more time : [^\]]+
  • and a ] character : \]

Note that [ and ] have a special meaning -- which means you have to escape them when you want them to be interpreted literally.

Pascal MARTIN
A: 

I found this from this source. All credit goes to the author, ShEx.

function stripBBCode($text_to_search) {
    $pattern = '|[[\/\!]*?[^\[\]]*?]|si';
    $replace = '';
    return preg_replace($pattern, $replace, $text_to_search);
    }

echo stripBBCode($text_to_search);

I've tested it and it does work.

Rupert
i think this strip the content too :)
David
It works with the example you gave but I haven't tried it on more complex examples.
Rupert