3

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

Kyle Rosendo
  • 24,405
  • 7
  • 77
  • 115
CodeOverload
  • 45,400
  • 52
  • 128
  • 215

2 Answers2

21

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
  • 385,748
  • 76
  • 642
  • 654
-1

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 Madden-Abbott
  • 12,568
  • 14
  • 57
  • 70