BBcode originated from its early use in Ultimate Bulletin Board , widely considered to be the first real discussion forum. Since that time the majority or major discussion and bulleting boards (such as vBulletin and phpBB ) have adopted BB code in one way or another.
Why use BBcode instead of HTML? In most cases, allowing users to enter HTML inside their message is impractical for both security and stylistic reasons. BB Code is used as an alternative to raw HTML and limits the kind of formatting that can be applied to text in a post.
There is no industry standard that applies to BB code so the implementation is essentially up to the discretion of the application designer. It also means that there are countless variations of the code in use. Such 'non-standard' functionality might include a tag that renders a YouTube video, or another to highlight PHP code.
Basic BB Code Examples
Code: This is an example of [b]bold[/b]
Result: This is an example of bold
Code: This is an example of [u]underlined[/u] text and this is text in [i]italics[/i].
Result: This is an example of underlined text and this is text in italics
Below are two functions that permit you to implement BBcode into your basic applications.
This first (cheap & nasty) function simply demonstrates usage of the PHP str_replace function. We're sharing this simply because we included it in the original 2009 Internoetics article.
The above will output "This is bold and this is underlined and this is in italics.
This second function is faster and more robust than the simple implementation above. It uses a
$find array and a
$replace array, and then uses the PHP preg_replace function to generate your text.
Strip BBcode from Text
If you want to strip BBcode from text you can use this function.
Checking Valid Tags
Checking for valid opening and closing tags becomes rather complex. We wrote the following function shortly after we first published this on Internoetics in 2009. It's become a little redundant now with the excellent packages that are available... but we'll share it anyhow. It simply counts the number of opening and closing tags for each permitted BB Code type. If they're uneven it records an error (with tag count) and returns the result in an array.
The resulting array will look something like this:
If you're going to return how many tags were in error, take into account that the total result may return an odd number.
Following is a rather generic function to simply return each identified tag error (ignoring the count).
The function will return basic text. Example:
Review invalid [b], [i], [h2], [url] tags. Ensure they are opened and closed correctly.
The Best Solution
The complexity of BB Code means that the markup is better served by one of the many packaged libraries available online. There are plenty on Github, PHPclasses, and elsewhere.
The download includes the sample functions on this page.