Back PHP

BB Code to HTML Parser with PHP

WRITTEN BY ON 06 Jan 2011
20,875 VIEWS • SHARES
5 comments

This function parse string that consists BB Code to HTML. It's really useful when you don't want user to use HTML tags to avoid XSS attack. Due the the simplicity of this script, it's very easy to reverse the parser to convert HTML to BBCode as well.

PHP

Simply call the function by passing your string you wish to parse. To convert the parser to HTML to BB Code, change this line:

$newtext = str_replace($bbcode, $htmlcode, $text);

to

$newtext = str_replace($htmlcode, $bbcode, $text);

function bb2html($text)
{
  $bbcode = array("<", ">",
                "[list]", "[*]", "[/list]", 
                "[img]", "[/img]", 
                "[b]", "[/b]", 
                "[u]", "[/u]", 
                "[i]", "[/i]",
                '[color="', "[/color]",
                "[size="", "[/size]",
                '[url="', "[/url]",
                "[mail="", "[/mail]",
                "[code]", "[/code]",
                "[quote]", "[/quote]",
                '"]');
  $htmlcode = array("&lt;", "&gt;",
                "<ul>", "<li>", "</ul>", 
                "<img src="", "">", 
                "<b>", "</b>", 
                "<u>", "</u>", 
                "<i>", "</i>",
                "<span style="color:", "</span>",
                "<span style="font-size:", "</span>",
                '<a href="', "</a>",
                "<a href="mailto:", "</a>",
                "<code>", "</code>",
                "<table width=100% bgcolor=lightgray><tr><td bgcolor=white>", "</td></tr></table>",
                '">');
  $newtext = str_replace($bbcode, $htmlcode, $text);
  $newtext = nl2br($newtext);//second pass
  return $newtext;
}

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

5 comments
Fliggerty 5 years ago
Thank you, this is exactly what I was looking for!

I will point out that there are some quotes that ought to be apostrophes in there though, such as "[size="". But it was easily remedied, and this function does exactly what I need.

So thanks again!
Reply
roggy 5 years ago
bad for XSS attack: [url="http / / " script="javascript:doevel();"]url[/url]
Reply
WeeDzCokie 4 years ago
You can run a preg_match on the string that is going to be inserted to the page/database and check for any line that matches <a *text* script=""></a> and remove that line
Reply
WeeDzCokie 4 years ago
@roggy
To prevent script injection couldn't you make a bbcode tag "script=" and have it replaced with a different html tag
Reply
Onur 3 years ago
Hi,

This function can add smilies?

ty.
Reply