Simple Way of Implementing BBCode with PHP

Simple Way of Implementing BBCode with PHP

When posting on forums, we usually use BBcode for styling our texts. When developing webpages, if we want to let our users style their profiles but don’t want to give them permission to style directly with CSS or html (<strong> etc..), we could simply use this piece of code to let them use those BBcodes.

Please note that we could do this using REGEX but as I used the word ‘simple’ in the title of the post, I’m going to make it really simple :)

The first thing we do is create an array with the tags we are going to use. In my case, my array is $bbcode and I’m going to use codes in square brackets, just as forum platforms do. Take a look at the code, you will see it really is simple.

$bbcode = array(
    "[big]" => "<big>",
    "[/big]" => "</big>",
    "[b]" => "<strong>",
    "[/b]" => "</strong>",
    "[i]" => "<em>",
    "[/i]" => "</em>",
    "[u]" => "<u>",
    "[/u]" => "</u>",
    "[img]" => "<img src=\"",
    "[/img]" => "\" border=\"0\" />",
    "[sup]" => "<sup>",
    "[/sup]" => "</sup>",
    "[sub]" => "<sub>",
    "[/sub]" => "</sub>",
    "[quote]" => "<span class=\"quote\">",
    "[/quote]" => "</span>",

As you can see, for the quotes I use a SPAN element with class=”quote” but it could be a DIV as well, since I’m styling it as a block element in my CSS file.

Next, to change our text into the styled one, all we have to do is use the strtr function and use our array as the – guess what – array with replace pairs.

echo strtr('Hello. I am [b]bolded[/b], I am [u]underlined[/u] and I am [big]big[/big]!', $bbcode);

That’s it! As Duke Nukem would say.. piece of cake.

Have swing!

ps. I know it doesn’t include the useful codes as [url] but for that we should already use regex.

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: