BB Code to HTML Parser with PHP

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.


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);


$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;

Share the love

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!