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 


[color=blue]blue text[/color]


<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.


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 File

Some preparation work must be done before the UBB code parsing takes place. This work is all moved to the 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 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:

Use BB Code in Your PHP Application

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:

Use BB Code in Your PHP Application

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=]Don't panic![/quote]   
if ($code) {       echo "Code in fixed-width font";   }
[img][/img]   [img w=80 h=25] [/img]  

[email protected]   [email][email protected][/email]   [[email protected]]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: Use BB Code in Your PHP Application
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.  Use BB Code in Your PHP Application
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 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 —
  • 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 –
 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.


Category: programming Time: 2005-02-22 Views: 1

Related post

  • Highlight Source Code in Your PHP Application 2005-04-11

    If you run a Website about programming, chances are that you display source code on your site's pages. Wouldn't it be great if the source code was highlighted - displayed using different colors - in the same way the desktop programming editors and ID

  • Is Your PHP Application Affected by the Y2K38 Bug? 2010-08-24

    I don't want to be too alarmist, but try running the following PHP code on your system: <?php $date = '2040-02-01'; $format = 'l d F Y H:i'; $mydate1 = strtotime($date); echo '<p>', date($format, $mydate1), '</p>'; ?> With luck, you'll s

  • Js file is not adding using this code in functions.php 2014-09-15

    Sorry i am noob in WordPress. I am using following code in functions.php to add the .js file in wordpress. function your_function_name() { wp_localize_script( 'function', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); wp_enq

  • Use jEdit to Edit Your PHP 2005-02-08

    If you're looking for a free (donationware), open source text editor for PHP scripts, I recommend that you try jEdit. This is a mature, Java-based programmer's text editor with an excellent set of core features, plus many more that can be added via "

  • Can apache expose the ldap group used to authenticate to a php application? 2015-10-28

    I have a LAMP server setup using Apache2, mod_php, and mod_authnz_ldap to authenticate to Active Directory. This hosts a lightweight php application where users enter and manipulate data. Access is based on 'require ldap-group ...' directives, and a

  • Preventing mysql deadlocks in your php application that uses SELECT- LOCK IN SHARE MODE 2011-10-18

    If I understand SELECT ... LOCK IN SHARE MODE correctly, you can place it into a mysql transaction to select the rows you will be working with during that transaction. This is done in order to "lock out" those selected rows from other session's

  • Should You Close Your PHP Code Tags? 2010-09-18

    Even those with a modest grasp of PHP know that code must be enclosed within special <?php and ?> tags. note: Alternative PHP tags You may also be aware that PHP code can be delimited with the lesser-used <script language="php"> and

  • Applications using GPL code and run-time libraries of proprietary IDEs 2014-10-11

    The GPL is described as a 'highly viral' license (if an application contains code which is licensed under GPL, distribution requires open sourcing of the whole application). Do I understand correctly that linking GPL code with closed source run-time

  • Pimp Your PHP App with Flex! 2009-04-29

    If you're looking to add some pizzazz to your PHP application, look no further – Adobe's Flex is here to give your interface some polish. In this article Lennart Steinke shows us how to make a Flex widget with a PHP back end. Read carefully, because

  • Localizing PHP Applications "The Right Way", Part 1 2011-10-28

    Localizing PHP Applications "The Right Way" Localizing PHP Applications "The Right Way", Part 1 Localizing PHP Applications "The Right Way", Part 2 Localizing PHP Applications "The Right Way", Part 3 Localizing PHP

  • Localizing PHP Applications "The Right Way", Part 2 2011-11-02

    Localizing PHP Applications "The Right Way" Localizing PHP Applications "The Right Way", Part 1 Localizing PHP Applications "The Right Way", Part 2 Localizing PHP Applications "The Right Way", Part 3 Localizing PHP

  • Localizing PHP Applications "The Right Way", Part 5 2011-11-25

    Localizing PHP Applications "The Right Way" Localizing PHP Applications "The Right Way", Part 1 Localizing PHP Applications "The Right Way", Part 2 Localizing PHP Applications "The Right Way", Part 3 Localizing PHP

  • The PHP Application Environment 2016-06-15

    The following is a short extract from our recent book, Jump Start PHP Environment, available for free to SitePoint Premium members. Print and ebook copies are sold in stores worldwide, or you can order them here. We hope you enjoy this extract and fi

  • How To Synchronize Your PHP and MySQL Timezones 2011-04-19

    PHP and MySQL are separate processes with their own default timezone configurations. You're unlikely to run into timezone issues during development or if you're deploying a single web application to your server. In that situation, PHP and MySQL can u

  • What's a good setup for running Java and PHP applications with SSL on the same server? 2011-05-26

    I have one Java- and one PHP-application which I both want to run on the same machine (using Tomcat). As far as I can see, I have two options: Option 1: Do the classic apache-tomcat setup with mod_jk and let apache handle the php requests and forward

  • using custom fields on content.php file of my theme 2012-05-22

    is there any error in following code? when i use following code in content.php file of my theme, then nothing is displayed on blog, it seems there is some error. and when i comment folowing code everything gets back to normal. <?php if (empty(get_cus

  • Intrusion Detection For PHP Applications With PHPIDS 2013-01-05

    Intrusion Detection For PHP Applications With PHPIDS Version 1.0 Author: Falko Timme This tutorial explains how to set up PHPIDS on a web server with Apache2 and PHP5. PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast

  • Using YAML in Your PHP Projects 2012-07-23

    Test fixtures, configuration files, and log files all need to be both human and machine readable. YAML (YAML Ain't Markup Language) is a less-verbose data serialization format than XML and has become a popular format among software developers mainly

  • Keeping Your PHP Code Well Documented 2014-02-17

    Introduction Pretty much every PHP developer writes comments along with the actual code. But the language itself doesn't impose any rules on how to do so. You just have to wrap them around some specific tags and then you can write any content you wan

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 3.060 (s). 13 q(s)