Parsing BBCode in a PHP script

Parsing BBCode in a PHP script
Difficulty: Easy
Description: How to create a script that will parse defined BBCode tags.
Author: M@ster; Date Added: 2008-10-12; Views: 11170
Well if you've ever joined a forum/community when you go to post most of the time they will have BBCode enabled, but what if you want to make your own application and allow BBCode. Well here's a guide that will explain how you can allow BBCode.

Lets say you're getting your text/message from a mysql database and you want to take the message and enable it and turn BBCode into html. First of all you need to get the variable for that message.


$text = $row['message'];

And the other code that will turn the BBCode into html. Heres an example for making bold text:

//the pattern to be matched
$pattern[0] = "/[b](.*?)[/b]/is";

//the replacement
$replace[0] = "$1";

//the variable for the replace
$text = preg_replace($pattern, $replace, $text);

And then when you want to display it out on the page just use echo.

If you want to add more patterns to replace just use these:

$pattern[1] = "";
$replace[1] = "";

$pattern[2] = "";
$replace[2] = "";

$pattern[3] = "";
$replace[3] = "";

$pattern[4] = "";
$replace[4] = "";

Change the number when adding a new pattern and replace.

Hope this tutorial helped!