How to remove BB codes from a string?
Question
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
Solution
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 :
[^\]]+
- 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.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow