Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

BBcode with PHP

Bulletin Board Code or BB Code is a lightweight markup language used to format text within posts made on the majority of message board platforms, although it's now widely used in any application that permits posts, comments or contributions from users. The available BBcode tags (similar to HTML) - usually indicated by square brackets surrounding text - are parsed server-side before being translated into a markup language that web browsers can render - such as HTML. While BB tags can be typed manually around text content, you'll find in many cases there's a JavaScript-powered WYSIWYG interface (not unlike the WordPress editor) that allows for simple point-and-click content formatting.

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 underlined text and this is text in [i]italics[/i].
Result: This is an example of underlined text and this is text in italics

PHP Functions

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.

1
<?php 
2
/*
3
 BBcode with PHP
4
 http://www.beliefmedia.com/php-bbcode
5
*/
6
 
7
function beliefmedia_basic_bbcode($text) {
8
 
9
  $text = str_replace(&quot;[b]&quot;, &quot;<b>&quot;, &quot;$text&quot;);
10
  $text = str_replace(&quot;[/b]&quot;, &quot;</b>&quot;, &quot;$text&quot;);
11
  $text = str_replace(&quot;[u]&quot;, &quot;<u>&quot;, &quot;$text&quot;);
12
  $text = str_replace(&quot;[/u]&quot;, &quot;</u>&quot;, &quot;$text&quot;);
13
  $text = str_replace(&quot;[i]&quot;, &quot;<i>&quot;, &quot;$text&quot;);
14
  $text = str_replace(&quot;[/i]&quot;, &quot;</i>&quot;, &quot;$text&quot;);
15
 
16
 return $text;
17
}
18
 
19
/* Usage */
20
$text = 'This is [b]bold[/b] and this is [u]underlined[/u] and this is in [i]italics[/i].';
21
echo beliefmedia_basic_bbcode($text);
22
?>

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.

1
<?php 
2
/*
3
 BBcode with PHP (preg_replace)
4
 http://www.beliefmedia.com/php-bbcode
5
*/
6
 
7
function beliefmedia_bbcode($text){
8
   $find = array('~\[b\](.*?)\[/b\]~s', '~\[i\](.*?)\[/i\]~s', '~\[u\](.*?)\[/u\]~s', '~\[size=(.*?)\](.*?)\[/size\]~s', '~\[color=(.*?)\](.*?)\[/color\]~s');
9
   $replace = array('<b>$1</b>', '<i>$1</i>', '<span style=&quot;text-decoration:underline;&quot;>$1</span>', '<span style=&quot;font-size:$1px;&quot;>$2</span>', '<span style=&quot;color:$1;&quot;>$2</span>');
10
 return preg_replace($find, $replace, $text);
11
}
12
 
13
/* Usage */
14
echo beliefmedia_bbcode('This is [b]bold text[/b].');
15
echo beliefmedia_bbcode('This text [i]italic[/i] text.');
16
echo beliefmedia_bbcode('This is [u]underlined[/u] text.');
17
echo beliefmedia_bbcode('this is [size=18]18px[/size] font.');
18
?>

Strip BBcode from Text

If you want to strip BBcode from text you can use this function.

1
<?php 
2
/*
3
 BBcode with PHP (Strip BB Code)
4
 http://www.beliefmedia.com/php-bbcode
5
*/
6
 
7
function beliefmedia_strip_bbcode($text) {
8
  $pattern = '|[[\/\!]*?[^\[\]]*?]|si'; $replace = '';
9
 return preg_replace($pattern, $replace, $text);
10
}
11
?>

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.

1
<?php 
2
/*
3
 BBcode with PHP (Check if any unclosed tags)
4
 http://www.beliefmedia.com/php-bbcode
5
*/
6
 
7
function beliefmedia_check_bbcode($text) {
8
 
9
    $result = '';
10
 
11
    $permitted_tags = array(&quot;b&quot;, &quot;i&quot;, &quot;u&quot;, &quot;h1&quot;, &quot;h2&quot;, &quot;url&quot;);
12
    $result_array = array();
13
 
14
    foreach ($permitted_tags as $tag) {
15
 
16
        /* How often is the tag open? */
17
        preg_match_all ('/\[' . $tag . '(=[^ ]+)?\]/i', $text, $matches);
18
        $opentags = count($matches['0']);
19
 
20
        /* How often is the tag closed? */
21
        preg_match_all ('/\[\/' . $tag . '\]/i', $text, $matches);
22
        $closetags = count($matches['0']);
23
 
24
        /* Number tags unclosed? */
25
        $unclosed = $opentags - $closetags;
26
        $sign = min(1, max(-1, $unclosed));
27
 
28
        /* Build resulting array list */
29
        if ($opentags != $closetags) {
30
            $result_array[&quot;$tag&quot;]['open'] = $opentags;
31
            $result_array[&quot;$tag&quot;]['closed'] = $closetags;
32
        }
33
 
34
    }
35
 
36
 return $result_array;
37
}
38
 
39
/* Usage */
40
$text = '[b]bold ok[/b] [/b]bold unclosed[/b] [/b]another bad format[b] [/b]starting bold unclosed[b] [i]italic unclosed[i] [i]italic[/i] [h2]heading unclosed[h2] [url]http://www.beliefmedia.com[url] [h1]valid h1[/h1]';
41
echo 'pre' . print_r(beliefmedia_check_bbcode($text), true) . '/pre';

The resulting array will look something like this:

1
Array
2
(
3
    [b] => Array
4
        (
5
            [open] => 2
6
            [closed] => 6
7
        )
8
 
9
    [i] => Array
10
        (
11
            [open] => 3
12
            [closed] => 1
13
        )
14
 
15
    [h2] => Array
16
        (
17
            [open] => 2
18
            [closed] => 0
19
        )
20
 
21
    [url] => Array
22
        (
23
            [open] => 2
24
            [closed] => 0
25
        )
26
 
27
)

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

1
<?php 
2
/*
3
 BBcode with PHP (Sample usage, using text from above)
4
 http://www.beliefmedia.com/php-bbcode
5
*/
6
 
7
function beliefmedia_bbcode_error($text) {
8
 
9
  /* Check for unclosed tags */
10
  $result = beliefmedia_check_bbcode($text);
11
 
12
  /* If not empty, results we'll loop through array */
13
  if (!empty($result)) {
14
 
15
    foreach ($result AS $tags => $count) {
16
      $return .= '[' . $tags . '], ';
17
    }
18
 
19
    /* Curate result */
20
    $return = 'Review invalid ' . rtrim($return, ', ') . ' tags. Ensure they are opened and closed correctly';
21
    return $return;
22
 
23
  } else return false;
24
}
25
 
26
/* Sample function usage */
27
echo beliefmedia_bbcode_error($text);

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.

Download

The download includes the sample functions on this page.


Title: BBcode with PHP
Description: Sample BB Code PHP functions that accompany our introductory article.
  Download • Version 0.2, 1.3K, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433