BBcode is what “forumers” (or people who often visit forums and post messages there) use to format their posts in a multi-threaded message board that is often used in different community websites such as Grabeh (http://www.grabeh.com/), Philweavers (http://www.philweavers.net), Hook-up (http://www.hook-up.ph) Pinoyblog (http://www.pinoyblog).
And in this age of blogging, bloggers also use BBcode to format their entries. BBcode is also used in the comment feature of their blog or even in add-ons such as tag-board. Having some form of BBcode gives users the ability to make texts appear bold, italic, underlined, or stricken (as in strike a portion of a text). The user can also add hyperlinks and embed images. A lot more can be done with some form of BBcode besides what I just mentioned, and you can even design or create your own BBcode to specifically do stuff you want done.
So, if you are developing a Content Management System that will let users publish articles and perform other tasks with the same purpose, but you feel the need to disable the html tags, then it’s useful to add a BBcode feature to your CMS, thus allowing your users to format content. The question now is, how can you implement such a feature?
There are several ways to do it and one of them involves using the native functions of PHP such as preg_replace(), str_replace() and ereg_replace. Another method involves using a PEAR module but here we will focus only on using the PHP native functions to avoid a lengthy explanation on the pre-requisites for a PEAR module (which will mean a discussion that is much, much longer than this article).
A simple BBcode can be accomplished by using str_replace; if you don’t know much about regular expressions then this function should be good enough. It allows you to use a simple BBcode for the most essential formatting needs such as bold, italic, strike, underline and other things that you may need. It doesn’t have any additional parameters except the usual [starttag] some text [/endtag] syntax. You will have to use str_replace twice for each BBcode as you replace the [starttag] and the [endtag].
But if you think that you want to add a complicated BBcode that allows users to add links and embed images then the functions preg_replace and ereg_replace will be of use to you. I recommend that you use preg_replace instead of ereg_replace not just because of the PERL-like syntax on regular expressions but because preg_replace is faster than ereg_replace. Basic information regarding this subject is available at http://www.tote-taste.de/X-Project/regex/syntax.html.
Of course, the best way to implement this feature is by using regular expressions with preg_replace because you can simplify multiple lines via str_replace and compress them into just three lines. I’m providing some supplemental codes for this article at http://www.albrine.com and you can use the codes to implement stuff related to this article.