Use BB Code in Your PHP Application

Share this article

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:

  1. Set up your code environment

  2. Use PEAR’s BBCodeParser

  3. Customize the parser using configuration options

  4. 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_gpc option is ON

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_BBCodeParser class should be created
  • The methods setText() and parse() 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:

1460_1

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 &lt;, all > into &gt; 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]

Configuration Options

In addition to the UBB tags listed above, many other tags come shipped with the BBCodeParser and are available for your use. In order to benefit from them, however, you must first configure the parser, which is done using an “INI” (initialization) file. A sample INI file is included in this article’s code archive, located in the examples/ directory of the BBCodeParser package.

You can use this INI file from its original location or copy it to a handy directory of your choice, for example, your root testing directory. Then, go back to the test file through which the HTML_BBCodeParser class is created and change the instantiating line:

$options = @parse_ini_file('BBCodeParser.ini');  
$parser = new HTML_BBCodeParser($options);

By doing this, you supply to the class all the options that are read from the INI file. You can change the path and the name of the INI file if needed.

The INI File

The most important configuration item you can set in the INI file is this line:

filters     = Basic,Extended,Links,Images,Lists,Email

This tells the parser which filters are to be parsed and which should be ignored. A filter is simply a PHP class used by the BBCodeParser that defines a set of BB tags. The table below describes which BB tags each BBCodeParser filter gives you:

1460_table

The key benefit of the parser is that it can be configured to allow or disallow tags or groups of tags. If, for example, you use this parser in your CMS and you don’t want to allow the client to add images, because you’re afraid they might mess up your nice design, you can remove the Images filter via the INI file.

Other config options you may want to change in the INI file are:

  • “quotestyle” — you can set this value to “double” to be XHTML-compliant
  • “open” and “close” entries — you may want to enclose their default values with quotes if you’re running PHP5

Here’s how these settings will appear in your INI file:

quotestyle  = double  
open        = "["  
close       = "]"

The test script bb_test3.php and the INI file BBCodeParser.ini are included in the code archive for this article.

UBB Code Syntax

At this point, you may well be thinking, “Oh, no! Not another markup language to learn…” Don’t worry; chances are that you and your users already know most of these tags. If, for example, you’ve ever posted in a phpBB-based forum, such as the SitePoint Forums, or its blog and article comments, you know about UBB code.

It’s fair to say, though, that some of the tags might require further clarification, since almost every UBB code implementation is a sort of a UBB dialect. Not to worry — there’s an easy way to get the hang of it. You can learn the UBB code syntax, and at the same time test your parsing script, by pasting the following user input in the text area of your test script. Then, sit back and admire the results.

[color=red]I'm red and I'm hot[/color]  
[size=16]16pt sized text. That's big.[/size]  
[font=Verdana]I can use all kinds of fonts![/font]  
[align=right]This chunk is aligned to the right[/align]  
[align=center]I'm centered[/align]  
Hey, [quote=http://www.h2g2.com]Don't panic![/quote]  
if ($code) {  
   echo "Code in fixed-width font";  
}
 
 
[img]https://www.sitepoint.com/images/sitepoint-logo.gif[/img]  
[img w=80 h=25]https://www.sitepoint.com/images/sitepoint-logo.gif [/img]  
 
http://www.sitepoint.com  
https%3A%2F%2Feditor.sitepoint.com  
https%3A%2F%2Feditor.sitepoint.com  
https%3A%2F%2Feditor.sitepoint.com  
 
https%3A%2F%2Feditor.sitepoint.com  
 
moi@example.org  
[email]toi@example.org[/email]  
[email=we@example.org]drop us an email[/email]  
 
[ulist]  
   [*]one  
   [*]two  
[/ulist]  
 
[list]  
   [*]first  
   [*]second  
[/list]  
 
[list=1]  
   [*]ordered item 1  
   [*]and ordered item 2  
[/list]  
 
[list=i]  
   [*]ordered item 1 type i  
   [li=4]ordered item 4 type i[/li]  
[/list]  
 
[list=I]  
   [*]ordered item 1 type I  
[/list]  
 
[list=a s=5]  
   [li]ordered item 5 type a[/li]  
   [*]ordered item 6 type a  
[/list]  
 
[list=A]  
   [li]ordered item 1 type A[/li]  
   [li=12]ordered item 12 type A[/li]  
[/list]  
 
[list=A s=3]  
   [li]ordered item 1, nested list:  
           [li]nested item 1[/li]  
       [list=I]  
           [li]nested item 2[/li]  
       [/list][/li]  
   [li]ordered item 2[/li]  
[/list]

Here’s how the results should appear:

1460_2

You can use CSS to refine the display of some of the tags, including <a>, <code>, <q> (the [quote] BB tag) and so on. Optionally, you can also use nl2br() to convert new lines to <br />.

Create Your Own BB Tags

Like it so far? Well, now’s the time for you to step up and take full control over your destiny! Or, in other words, to customize the parser at will.

In this section, you’ll create you own custom parser filter and custom BB tags. Let’s call the filter MyBB, and the tags [h], [line] and [block]. When these tags are parsed, they’ll be replaced with the good old HTML tags <h1>, <hr /> and <blockquote>.

In order to do so, you’ll need to create a class definition for the MyBB filter. The class needs to:

  • be named HTML_BBCodeParser_Filter_MyBB
  • extend the base HTML_BBCodeParser class
  • be placed in a MyBB.php file
  • be located in YourPEARDir/HTML/BBCodeParser/Filter

Without further ado, here’s the code you need to have in the MyBB.php file in order to provide the heading, horizontal line and block quote formatting features:

<?php  
require_once 'HTML/BBCodeParser.php';  
 
class HTML_BBCodeParser_Filter_MyBB extends HTML_BBCodeParser  
{  
   var $_definedTags =  
       array('block' => array( 'htmlopen'  => 'blockquote',  
                               'htmlclose' => 'blockquote',  
                               'allowed'   => 'all',  
                               'attributes'=> array()  
                               ),  
             'line' =>  array( 'htmlopen'  => 'hr',  
                               'htmlclose' => '',  
                               'allowed'   => 'all',  
                               'attributes'=> array()  
                               ),  
             'h' =>     array( 'htmlopen'  => 'h1',  
                               'htmlclose' => 'h1',  
                               'allowed'   => 'all',  
                               'attributes'=> array()  
                               ),  
       );  
 
}  
?>

The only thing left is to add MyBB to the INI file’s filter line:

filters     = Basic,Extended,Links,Images,Lists,Email,MyBB

You’re done! Here are the custom tags in action.

1460_3

Related Files


That’s it for this BB tags tutorial. You’ve learned something you can start using right away to enrich your applications!

Firstly, visit http://pear.php.net and download PEAR libraries free of charge. This is a good idea, as it allows you to flex you sysadmin muscles a bit as you install PEAR. If you remember what we said in the setup section of this tutorial, all you need is the PEAR base classes and the BBCodeParser package.

Here are the other files that were created and used in this tutorial, and which are available in the code archive:

  • Directory structure — a text file that shows the directory structure I used for the examples, provided for your reference only in directory_structure.txt
  • Initialization script — init.inc.php
  • Test scripts — test1.php, test2.php and test3.php
  • The custom filter, which should be saved in YourPEARDir/HTML/BBCodeParser/Filter/MyBB.php — MyBB.php
  • The configuration file — BBCodeParser.ini
  • Everything as a zip file – bb.zip
Experiment … and Stay Tuned

You know that the best way to learn is by doing, so go ahead: set up your environment, run the examples and try them out. Adding BB code functionality to your CMS (guestbook/blog/forum/you-name-it) has never been easier!

… and stay tuned for the next part of this tutorial.

Frequently Asked Questions (FAQs) about BBCode in PHP Applications

What is BBCode and how is it used in PHP applications?

BBCode, or Bulletin Board Code, is a lightweight markup language used to format posts in many message boards. In PHP applications, BBCode is used to allow users to add styling to their messages, such as bold text, italics, colors, links, and more. It’s a safer and simpler alternative to allowing users to use HTML in their posts, which can pose security risks.

How can I implement BBCode in my PHP application?

Implementing BBCode in your PHP application involves parsing the BBCode tags in the user’s input and replacing them with the corresponding HTML tags. This can be done using built-in PHP functions or third-party libraries. The article provides a detailed guide on how to implement BBCode in a PHP application.

What are some common BBCode tags and their uses?

Some common BBCode tags include [b] for bold text, [i] for italic text, [u] for underlined text, https%3A%2F%2Feditor.sitepoint.com for hyperlinks, [img] for images, and [color] for colored text. These tags are used by enclosing the desired text in the tags, like so: [b]bold text[/b].

Are there any security concerns when using BBCode in PHP applications?

While BBCode is generally safer than allowing users to input raw HTML, there are still potential security concerns. For example, users could potentially insert harmful scripts or inappropriate content through BBCode tags. It’s important to sanitize user input and implement proper security measures when using BBCode.

Can I customize the appearance of BBCode in my PHP application?

Yes, you can customize the appearance of BBCode in your PHP application by modifying the HTML that the BBCode tags are replaced with. For example, you could change the [b] tag to produce red bold text instead of the default black bold text.

How can I prevent users from misusing BBCode in my PHP application?

You can prevent misuse of BBCode by implementing restrictions on which tags can be used, limiting the number of tags in a single post, or even disabling BBCode entirely for certain users. It’s also important to provide clear instructions to users on how to use BBCode correctly.

Can I add custom BBCode tags to my PHP application?

Yes, you can add custom BBCode tags to your PHP application. This involves adding new rules to your BBCode parser to recognize the new tags and replace them with the appropriate HTML.

How can I test the BBCode implementation in my PHP application?

You can test the BBCode implementation in your PHP application by creating test posts with various BBCode tags and checking if they are correctly converted to HTML. It’s also a good idea to test edge cases, such as nested tags and incorrect tag usage.

Can I use BBCode in other programming languages besides PHP?

Yes, BBCode can be used in any programming language that can parse text. There are BBCode libraries available for many different programming languages, including JavaScript, Python, Ruby, and more.

Where can I find more resources on BBCode in PHP applications?

There are many resources available online for learning more about BBCode in PHP applications. The PHP documentation, online tutorials, and community forums are all great places to start.

Stoyan StefanovStoyan Stefanov
View Author

Stoyan is an engineer at Yahoo and the author the author of Object-Oriented JavaScript and other books and articles about web development. Outside work, his time is spent experimenting with random web technologies, blogging at phpied.com and playing the blues guitar to his daughters' despite their preference for Mickey Mouse CDs.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week