Article
Use BB Code in Your PHP Application
Many Websites allow visitors or administrators to contribute to the sites's content through various means: a Content Management System, forums, blogs, or other commenting systems. When you're building such sites, it's a good idea to provide users with the ability to enhance that content by posting formatted text.
Similarly, when building programming-related sites, a very attractive, but rare feature is the ability to highlight displayed programming code using different colors to denote different programming language keywords, functions, and so on.
This series of articles will provide you with everything you need to start:
- Using the so-called BB code to format Website content
- Coloring code of virtually any programming language used in your content
In this, part one of the guide, you'll learn how to use BB code in your PHP application.
What is BB Code?
BB code is a very simple set of instructions (also known as BB tags) that provide rules as to how a piece of text should be formatted. When a page that contains BB code is displayed in the browser, the BB tags are replaced with appropriate HTML tags that the browser can understand.
Note that the acronyms "UBB" and "BB" are used as synonyms in this tutorial. "BB" stands for "Bulletin Board"; "UBB" stands for "Ultimate Bulletin Board", probably the first Web-based bulletin board system.
Why Use BB Code?
BB code is widely used in community forum systems like phpBB or vBulletin. Chances are that your Website's visitors or content contributors are already familiar with it, or that they can catch up pretty quickly. BB tags can be typed manually; alternatively, site owners can build JavaScript-powered interfaces to allow for simpler point-and-click content formatting.
At the end of this tutorial, you'll be able to use BB code to transform strings like this:
[b]bold[/b] text into <b>bold</b> text
and:
[color=blue]blue text[/color]
into:
<span style="color: blue">blue text</span>
If you feel that the existing BB tags are not flexible enough for your site's content formatting, don't worry. At the end of the tutorial you'll know enough to create your own BB tags and, for example, to replace
[mytag]my content[/mytag]
with whatever you feel like!
In this tutorial, we'll follow 4 steps in learning how to use BB code:
- Set up your code environment
- Use PEAR's BBCodeParser
- Customize the parser using configuration options
- Create your own BB tags
Note that you can download all the code you'll need for this article -– it will make things easier as we progress through the steps.
Setup
Systems setup may not be your favorite task, but a little sysadmin work is required here. It most definitely pays off, as you'll see soon. If you like, you can skip the setup section for now. Feel free to move on to the sexier "Using BBCode Parser" section and return here when you're ready to test and experiment with the examples yourself.
PEAR setup
BBCodeParser is the name of the PHP library we'll use to process BB tags. It's a PEAR package, so you'll need PEAR installed. If you're already a PEAR convert, good for you! You can skip the next paragraph.
If you're new to PEAR or haven't yet taken The Step, today is a perfect day for you to do so -- and to start benefiting from this huge repository of high-quality PHP code. Here on SitePoint you'll find Getting Started with Pear, a great tutorial that explains how to install PEAR on your system and start to use it.
After you've installed the core PEAR libraries, you need to install the BBCodeParser package. You can use the PEAR installer or grab the package directly from the PEAR site and stick it into your PEAR codebase under the /HTML directory.
When you're done, your PEAR directory should look like this:
/PEAR
/HTML
/BBCodeParser
/example
/Filter
Basic.php
Email.php
...
BBCodeParser.php
/PEAR
/Command
/Frontend
PEAR.php
The init.inc.php File
Some preparation work must be done before the UBB code parsing takes place. This work is all moved to the init.inc.php file, to keep it separated from the rest of the installation.
The tasks we must complete include:
- Add the PEAR directory to the include path
- Strip slashes if the
magic_quotes_gpcoption isON
For the purposes of this tutorial, I have set up my PEAR directory as a subdirectory of the root tutorial directory that contains the example files; you can change the path to your PEAR directory if it's different.
The slash-stripper code is directly taken from the PHP manual's get_magic_quotes_gpc() entry.
The init.inc.php file is included in the the code archive for this article -- refer to the inline comments within that file for more information. Your testing scripts should start by requiring this init file.
The Test Scripts
To test the BB processing instructions you're about to learn, we'll use a simple form with one text area:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="text" style="width: 300px; height: 200px"><?php echo @$_POST['text']; ?></textarea>
<br />
<input type="submit" />
</form>
All our tests will contain this form. They'll be named with a bb_ prefix and a sequential number as a suffix.
That covers everything that's required to set up the environment. A text file containing the complete directory structure is included in this article's code archive, just to make sure you got it right.
Building on the BB Code Parser
Now, let's write some code that uses the BB code parser to display a properly formatted Web page.
A Simple Example
In the test scripts, we'll first check if the form was submitted; if it was, we'll parse the code in the 'text' field.
We need a few key elements in order to parse any BB code inserted into this 'text' field:
- An instance of
HTML_BBCodeParserclass should be created - The methods
setText()andparse()must be called - The results of our hard work will be retrieved using the
getParsed()method.
To make the results of the script execution stand out, we'll surround them with an orange border.
Here's the code required:
if (!empty($_POST['text'])){
echo '<div style="border: solid 1px orange; padding:20px; margin: 20px">';
require_once 'HTML/BBCodeParser.php';
$parser = new HTML_BBCodeParser();
$parser->setText($_POST['text']);
$parser->parse();
echo $parser->getParsed();
echo '</div>';
}
Here's the script in action:

Try it yourself! Extract the complete bb_test1.php file from this article's code archive and execute it in the environment you've already set up.
Use qParse() and Deal with HTML
The three methods in the above example, setText(), parse() and getParsed(), can be replaced by a single method call, qParse() -- "q" as in "quick".
If you don't want to execute the HTML code typed into the textarea, all you need is to make a call to htmlspecialchars(). This would make all < into <, all > into > and so on.
Here's the simplified and HTML-stripped version:
$parser = new HTML_BBCodeParser();
echo $parser->qParse(htmlspecialchars($_POST['text']));
Play around with the new bb_test2.php script included in the article's code archive. The basic UBB tags you can experiment with include:
[b]bold[/b]
[i]italics[/i]
[u]underlined[/u]
[s]stikethrough[/s]
[sub]subscript[/sub]
[sup]superscript[/sup]
Stoyan is an engineer at Yahoo and the author the author of