New Website

I've made a new website, as lynx.io is dead. You can find it here: http://macr.ae/—it's similar in format to lynx.io, but has better articles, and they're all written by me.

JavaScript disabled

While it will still mostly work, a lot of this site's functionality relies on JavaScript - please enable it for the best experience.

A basic BBCode parser

In this article I will show you and explain to you the basic BBCode parser I have built recently for one of my projects. It is lightweight and easy to modify, as it just uses regex. Let's jump in at the deep end and put all the code in one place:

<?php

function parse_bbcode($string) {
    $codes = array(
        '[b]{ALL}[/b]'                  => '<strong>$1</strong>',
        '[i]{ALL}[/i]'                  => '<i>$1</i>',
        '[u]{ALL}[/u]'                  => '<span style="text-decoration: underline">$1</span>',
        '[s]{ALL}[/s]'                  => '<span style="text-decoration: line-through">$1</span>',
        '[size={NUM}]{ALL}[/size]'      => '<span style="font-size: $1">$2</span>',
        '[url={URL}]{ALL}[/url]'        => '<a href="$1">$3</a>',
        '[color={STRING}]{ALL}[/color]' => '<span style="color: $1">$2</span>',
        '[font={STRING}]{ALL}[/font]'   => '<span style="font-family: $1">$2</span>',
        '[img]{URL}[/img]'              => '<img src="$1" alt="$1" />',
    );

    $replace = array(
        '['         => '\[',
        ']'         => '\]',
        '/'         => '\/',
        '{ALL}'     => '(.*)',
        '{URL}'     => '(https?:\/{2}[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,3}(\/\S*)?)',
        '{STRING}'  => '([a-z]+)',
        '{NUM}'     => '([0-9]+)',
    );

    foreach ($codes as $key => $code) {
        $bb_array['/' . str_replace(array_keys($replace), array_values($replace), $key) . '/i'] = $code;
    }

    $string = htmlspecialchars($string);
    $string = nl2br($string);
    return preg_replace(array_keys($bb_array), array_values($bb_array), $string);
}

It may look confusing at first, but it's actually pretty simple. I'm going to cycle through the code, explaining how it all works.

The $codes array is an array of all the BBCodes that you want. This is basically just there for people who don't understand regex, or find it easier to work with plain text. It also makes it easier to implement in environments such as bulletin boards where the administrator isn't necessarily a coder. The $replace array is an array of replacements to be made in order to change $codes into regex.

The foreach below that simply turns $codes into regex - it cycles through and str_replace's everything found in $replace. str_replace looks at a variable and replaces all occurrences of one string with another. For example:

<?php

$string = 'Hello world!';
$string = str_replace('orld', 'illiam', $string);
echo $string; // Hello william!

It also accepts arrays as arguments, for example:

<?php

$string = 'Hi world!';
$string = str_replace(array('orld', 'Hi'), array('illiam', 'Hello'), $string);
echo $string; // Hello william!

str_replace is case sensitive - for a case insensitive version, use str_ireplace instead.

 

Below that, we see the following two lines:

$string = htmlspecialchars($string);
$string = nl2br($string);

htmlspecialchars converts some special characters (specifically the ones that HTML doesn't get on with) to HTML entities. For example:

htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); //&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
htmlspecialchars("<a href='test'>Test</a>"); //&lt;a href='test'&gt;Test&lt;/a&gt;

nl2br means "new line to br". It literally does just that - converts all literal line breaks ("\n") to HTML line breaks ("<br />").

 

Then, on the final line:

return preg_replace(array_keys($bb_array), array_values($bb_array), $string);

preg_replace is similar to str_replace, but works with regex's instead of strings. For example:

<?php

$string = 'Hello world!';
$string = preg_replace('/[a-z]/i', 'b', $string);
echo $string; // bbbbb bbbbb!

So, the final line processes the regex's generated by the str_replace and produces the final string.

 

Usage

The function can be used like so:

echo parse_bbcode('[b]Hello world![/b] [url="http://lynx.io/"]lynx.io is awesome[/url]');

About Callum Macrae:

Callum Macrae is the founder of lynx.io and a JavaScript developer from the United Kingdom. He is currently writing his first book, to be published by O'Reilly Media.

You can view more articles by this author here.

Tags: php bbcode parsing preg_match regex

Comments

Emmanuel says:

Please i need the code to display PHP and HTML codes using BBCODES, all the ones i've being seeing have not being helpful.

Thanks!

cheap valentino shoes says:

Do you know that Andie <a href="http://www.valentinooutlets.net/"><strong>valentino outlet</strong></a> got the best fucking tits in the world? No? Now you know. Also her ass is another thing that’s awesome. You need such perfect butt. If you dont like fat butts, then her booty should be ok. I’ve seen the whole clip (this is just a sample) and later she masturbates like fucking crazy.To be honest with you I’ve seen A LOT of Andie Valentino’s clips but never saw her doing public nudity. So she’s having fun being completely naked in a public area, near some restaurant probably.<a href="http://www.valentinooutlets.net/">valentino outlet store </a> This vid is barely 1,5 minutes but I’ve tracked the source so if you like it you know where to go for more. She’s a cute little exhibitionist!Now that you’ve watched the vid let me suggest you one thing, you can do it or not – it’s your choice, I’m only going to tell you where to find the most amazing web sex cams , that’s all. Their girls are really pretty and kinky, the name is camsee dot us.<a href="http://www.valentinooutlets.net/"><strong>valentino outlet online</strong></a>This low quality video is surely somewhat unique. Why? Because not often you see two sexy chicks tickling each others feet…Both girls are laughing their asses off while they’re smothering their feet. Their names are: Jaime Hammer and of course Andie Valentino. Always good to watch something new, right?I like the way this clip was filmed.<a href="http://www.valentinoshoes.net/"><strong>valentino shoes</strong></a> The background is all red and there’s nothing but naked Andie Valentino so you won’t be distracted and it’s easy to focus on her perfect nude body. Her boobs are masterpiece. Her ass is out of this planet. She’s one of the top adult models of all time!<a href="http://www.valentinoshoes.net/"><strong>valentino shoes online </strong></a>I still can’t believe that her cleavage is all real…but it is, I’ve checked in various sources.and strips out of mentioned clothes! After she’s all naked she’s showing off her flexible skills! Her naked butt cheeks are like a dream come true for every admirer of the female beauty…of course her front side is no worse but let’s focus on her ass today!Tantalizing brown haired vixen Andie Valentino is posing in a set of black, lace lingerie in her luxurious canopy bed! Oh, she’s also wearing a diamond necklace but I think you’d prefer to see the diamond between her legs, lol. Too <a href="http://www.valentinoshoes.net/"><strong>cheap valentino shoes </strong></a>the site these pics were taken from is no longer working…or at least not in the time I was writing this…You’re looking at probably most recent images of the gorgeous Andie Valentino shot by Digital Desire. The curvy girl is stripping out of blue plush top and panties of the same colour…Sorry about <a href="http://www.vancleefarpelss.com/"><strong>van cleef arpels jewellery</strong></a>the censored crotch and stuff on the last three pics, but that’s how DD people want it. If you decide to join you’ll see everything, and what’s funny is that Andie’s pussy lips are constantly spreaded, like they want to eat you or something, lol.I’m not sure if high heels are the best thing to put on your feet when going out in the mountains, but that’s what Andie Valentino did. <a href="http://www.vancleefarpelss.com/"><strong>van cleef arpels</strong></a>She also put on a pair of tight, blue jeans and brown top. Quickly it turned out that she’s got no bra under it, <a href="http://www.salvatoreferragamos.org/"><strong>salvatore ferragamo</strong></a>and also that she wearing nice thong panties, underneath her denim pants…that’s just how she rolls.Take era in the street, too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for rich people do take era in street <a href="http://www.salvatoreferragamos.org/"><strong>ferragamo outlet</strong></a>, too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for the rich to make<a href="http://www.salvatoreferragamos.org/"><strong>salvatore ferragamo outlet </strong></a>", but the single look show you how can understand that those who like works of art like details? In the <a href="http://www.giuseppe-zanotti.org/"><strong>giuseppe zanotti</strong></a> Re-see after watching can truly be shaken to conquer the near distance single look show you how can understand that those who like works of art like details? In the Valentino 2015SS Re-see after watching can truly be shaken to conquer the near distance<a href="http://www.valentinooutlets.net/"><strong>http://www.valentinooutlets.net/</strong></a>.

cheap valentino shoes says:

Do you know that Andie [url=http://www.valentinooutlets.net/][b]valentino outlet[/b][/url] got the best fucking tits in the world? No? Now you know. Also her ass is another thing that’s awesome. You need such perfect butt. If you dont like fat butts, then her booty should be ok. I’ve seen the whole clip (this is just a sample) and later she masturbates like fucking crazy.To be honest with you I’ve seen A LOT of Andie Valentino’s clips but never saw her doing public nudity. So she’s having fun being completely naked in a public area, near some restaurant probably.[url=http://www.valentinooutlets.net/]valentino outlet store [/url] This vid is barely 1,5 minutes but I’ve tracked the source so if you like it you know where to go for more. She’s a cute little exhibitionist!Now that you’ve watched the vid let me suggest you one thing, you can do it or not – it’s your choice, I’m only going to tell you where to find the most amazing web sex cams , that’s all. Their girls are really pretty and kinky, the name is camsee dot us.[url=http://www.valentinooutlets.net/][b]valentino outlet online[/b][/url]This low quality video is surely somewhat unique. Why? Because not often you see two sexy chicks tickling each others feet…Both girls are laughing their asses off while they’re smothering their feet. Their names are: Jaime Hammer and of course Andie Valentino. Always good to watch something new, right?I like the way this clip was filmed.[url=http://www.valentinoshoes.net/][b]valentino shoes[/b][/url] The background is all red and there’s nothing but naked Andie Valentino so you won’t be distracted and it’s easy to focus on her perfect nude body. Her boobs are masterpiece. Her ass is out of this planet. She’s one of the top adult models of all time![url=http://www.valentinoshoes.net/][b]valentino shoes online [/b][/url]I still can’t believe that her cleavage is all real…but it is, I’ve checked in various sources.and strips out of mentioned clothes! After she’s all naked she’s showing off her flexible skills! Her naked butt cheeks are like a dream come true for every admirer of the female beauty…of course her front side is no worse but let’s focus on her ass today!Tantalizing brown haired vixen Andie Valentino is posing in a set of black, lace lingerie in her luxurious canopy bed! Oh, she’s also wearing a diamond necklace but I think you’d prefer to see the diamond between her legs, lol. Too [url=http://www.valentinoshoes.net/][b]cheap valentino shoes [/b][/url]the site these pics were taken from is no longer working…or at least not in the time I was writing this…You’re looking at probably most recent images of the gorgeous Andie Valentino shot by Digital Desire. The curvy girl is stripping out of blue plush top and panties of the same colour…Sorry about [url=http://www.vancleefarpelss.com/][b]van cleef arpels jewellery[/b][/url]the censored crotch and stuff on the last three pics, but that’s how DD people want it. If you decide to join you’ll see everything, and what’s funny is that Andie’s pussy lips are constantly spreaded, like they want to eat you or something, lol.I’m not sure if high heels are the best thing to put on your feet when going out in the mountains, but that’s what Andie Valentino did. [url=http://www.vancleefarpelss.com/][b]van cleef arpels[/b][/url]She also put on a pair of tight, blue jeans and brown top. Quickly it turned out that she’s got no bra under it, [url=http://www.salvatoreferragamos.org/][b]salvatore ferragamo[/b][/url]and also that she wearing nice thong panties, underneath her denim pants…that’s just how she rolls.Take era in the street, too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for rich people do take era in street [url=http://www.salvatoreferragamos.org/][b]ferragamo outlet[/b][/url], too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for the rich to make[url=http://www.salvatoreferragamos.org/][b]salvatore ferragamo outlet [/b][/url]", but the single look show you how can understand that those who like works of art like details? In the [url=http://www.giuseppe-zanotti.org/][b]giuseppe zanotti[/b][/url] Re-see after watching can truly be shaken to conquer the near distance single look show you how can understand that those who like works of art like details? In the Valentino 2015SS Re-see after watching can truly be shaken to conquer the near distance[url=http://www.valentinooutlets.net/][b]http://www.valentinooutlets.net/[/b][/url].

cheap valentino shoes says:

Do you know that Andie <a href="http://www.valentinooutlets.net/"><strong>valentino outlet</strong></a> got the best fucking tits in the world? No? Now you know. Also her ass is another thing that’s awesome. You need such perfect butt. If you dont like fat butts, then her booty should be ok. I’ve seen the whole clip (this is just a sample) and later she masturbates like fucking crazy.To be honest with you I’ve seen A LOT of Andie Valentino’s clips but never saw her doing public nudity. So she’s having fun being completely naked in a public area, near some restaurant probably.<a href="http://www.valentinooutlets.net/">valentino outlet store </a> This vid is barely 1,5 minutes but I’ve tracked the source so if you like it you know where to go for more. She’s a cute little exhibitionist!Now that you’ve watched the vid let me suggest you one thing, you can do it or not – it’s your choice, I’m only going to tell you where to find the most amazing web sex cams , that’s all. Their girls are really pretty and kinky, the name is camsee dot us.<a href="http://www.valentinooutlets.net/"><strong>valentino outlet online</strong></a>This low quality vi

cheap valentino shoes says:

Do you know that Andie <a href="http://www.valentinooutlets.net/"><strong>valentino outlet</strong></a> got the best fucking tits in the world? No? Now you know. Also her ass is another thing that’s awesome. You need such perfect butt. If you dont like fat butts, then her booty should be ok. I’ve seen the whole clip (this is just a sample) and later she masturbates like fucking crazy.To be honest with you I’ve seen A LOT of Andie Valentino’s clips but never saw her doing public nudity. So she’s having fun being completely naked in a public area, near some restaurant probably.<a href="http://www.valentinooutlets.net/">valentino outlet store </a> This vid is barely 1,5 minutes but I’ve tracked the source so if you like it you know where to go for more. She’s a cute little exhibitionist!Now that you’ve watched the vid let me suggest you one thing, you can do it or not – it’s your choice, I’m only going to tell you where to find the most amazing web sex cams , that’s all. Their girls are really pretty and kinky, the name is camsee dot us.<a href="http://www.valentinooutlets.net/"><strong>valentino outlet online</strong></a>This low quality video is surely somewhat unique. Why? Because not often you see two sexy chicks tickling each others feet…Both girls are laughing their asses off while they’re smothering their feet. Their names are: Jaime Hammer and of course Andie Valentino. Always good to watch something new, right?I like the way this clip was filmed.<a href="http://www.valentinoshoes.net/"><strong>valentino shoes</strong></a> The background is all red and there’s nothing but naked Andie Valentino so you won’t be distracted and it’s easy to focus on her perfect nude body. Her boobs are masterpiece. Her ass is out of this planet. She’s one of the top adult models of all time!<a href="http://www.valentinoshoes.net/"><strong>valentino shoes online </strong></a>I still can’t believe that her cleavage is all real…but it is, I’ve checked in various sources.and strips out of mentioned clothes! After she’s all naked she’s showing off her flexible skills! Her naked butt cheeks are like a dream come true for every admirer of the female beauty…of course her front side is no worse but let’s focus on her ass today!Tantalizing brown haired vixen Andie Valentino is posing in a set of black, lace lingerie in her luxurious canopy bed! Oh, she’s also wearing a diamond necklace but I think you’d prefer to see the diamond between her legs, lol. Too <a href="http://www.valentinoshoes.net/"><strong>cheap valentino shoes </strong></a>the site these pics were taken from is no longer working…or at least not in the time I was writing this…You’re looking at probably most recent images of the gorgeous Andie Valentino shot by Digital Desire. The curvy girl is stripping out of blue plush top and panties of the same colour…Sorry about <a href="http://www.vancleefarpelss.com/"><strong>van cleef arpels jewellery</strong></a>the censored crotch and stuff on the last three pics, but that’s how DD people want it. If you decide to join you’ll see everything, and what’s funny is that Andie’s pussy lips are constantly spreaded, like they want to eat you or something, lol.I’m not sure if high heels are the best thing to put on your feet when going out in the mountains, but that’s what Andie Valentino did. <a href="http://www.vancleefarpelss.com/"><strong>van cleef arpels</strong></a>She also put on a pair of tight, blue jeans and brown top. Quickly it turned out that she’s got no bra under it, <a href="http://www.salvatoreferragamos.org/"><strong>salvatore ferragamo</strong></a>and also that she wearing nice thong panties, underneath her denim pants…that’s just how she rolls.Take era in the street, too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for rich people do take era in street <a href="http://www.salvatoreferragamos.org/"><strong>ferragamo outlet</strong></a>, too many brands of compromise, and the official @Valentino micro-blog show even in this era never compromise to clear their position in which. Just as Valentino Garavani said: "I was designed for the rich to make<a href="http://www.salvatoreferragamos.org/"><strong>salvatore ferragamo outlet </strong></a>", but the single look show you how can understand that those who like works of art like details? In the <a href="http://www.giuseppe-zanotti.org/"><strong>giuseppe zanotti</strong></a> Re-see after watching can truly be shaken to conquer the near distance single look show you how can understand that those who like works of art like details? In the Valentino 2015SS Re-see after watching can truly be shaken to conquer the near distance<a href="http://www.valentinooutlets.net/"><strong>http://www.valentinooutlets.net/</strong></a>.

says:

Add comment

 

You can use markdown in comments (press "m" for a cheatsheet).

Enable JavaScript to post a comment

Markdown Cheat Sheet

# This is an <h1> tag
## This an <h2> tag
###### This is an <h6> tag

Inline markup: _this text is italic_, **this is bold**, and `code()`.

[Link text](link URL "Optional title")
[Google](http://google.com/ "Google!")

![Alt text](image URL)

![This is a fish](images/fish.jpg)

1. Ordered list item 1
2. Ordered list item 2

* Unordered list item 1
* Unordered list item 2
* Item 2a
* Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:

----

> This is a blockquote

This is an <h1> tag

This an <h2> tag

This is an <h6> tag

Inline markup: this text is italic, this is bold, and code().

Link text Google

This is a fish

  1. Ordered list item 1
  2. Ordered list item 2
  • Unordered list item 1
  • Unordered list item 2
    • Item 2a
    • Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:


This is a blockquote

Toggle MarkDown / HTML (t), full reference or close this