How to remove BB codes from a string?

How to get to all BBcodes in a row, but save the content?

Example:

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

Will be:

It is in bold and color.

+3
source share
2 answers

I suppose you could just use a regex and to replace everything between the and the empty string: preg_replace[]

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

The following is displayed:

This is bold and This is colored


Here the template I used matches:

  • a [:\[
  • Everything that is not a symbol ]:[^\]]
    • One or more times: [^\]]+
  • and ]:\]

Please note that [they ]are of particular importance - this means that you need to avoid them when you want to be interpreted literally.

+14

. , ShEx.

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

echo stripBBCode($text_to_search);

, .

0

Source: https://habr.com/ru/post/1741342/


All Articles