SITERAW

How to remove BBCode with PHP

Author Message
Locust # Posted yesterday
Removing BBCode tags from a string Hello

I have a little problem in PHP on a mini blog engine that I'm currently developing

the user enters a code provided with BBCode tags (a bit like on SiteRaw :D) and it formats the text automatically

up until that point, everything works works

on the other hand for the summary text I want to delete these BBCode tags completely

for example, this
[IMAGE] my image [/IMAGE]
Hello everybody
[YOUTUBE] my video [/YOUTUBE]
welcome to my super blog
should give me
Hello everybody
welcome to my super blog
I tried with str_replace but it leaves whatever content is between the BBCode tags

basically I'd like to do the equivalent of strip_tags but with BBCode tags rather than HTML

except that I do not see how

thank you
Ads
Kalvin # Posted two hours ago
Kalvin You need to build your own function with preg_replace as I doubt PHP will have a built-in solution specifically tailored towards BBCode.
Valter # Posted one hour ago
Valter Anytime you are dealing with variable content between your tags you must use regular expressions.

There is a tutorial on SiteRaw.

Code sample:
$text = '[IMAGE] my image [/IMAGE]
Hello everybody
[YOUTUBE] my video [/YOUTUBE]
welcome to my super blog'
;

$remove = ['IMAGE', 'YOUTUBE'];

$pattern = '~\[ (?:(?:' . implode('|', $remove) . ')] [^[]* \[/ )? [^]]* ]~iux';
$text = preg_replace($pattern, null, $text);

echo $text;
which gives you:
hello everyone welcome on my super blog
since there is no line-break.
Phoenix # Posted 37 minutes ago
Phoenix Nice use of delimiters, fagg0t.
Locust # Posted 5 minutes ago
Locust thanks

I will try with preg_replace then

Post a reply