on Fri Aug 22 01:14:47 GMT 2008 in PHP and viewed 6730 times
How to construct a function to build the useful BBCode that are used in most forums.
Everyone loves BBCode. It’s the cool code to use with the little b tags that makes your text bold and stuff. Well, this tutorial will demonstrate how to do the following:
Bold Text,
Italic Text,
Underlined Text,
Images,
Cancel Out HTML,
Break Lines,
Code Boxes, and
& to & to add to code validity
The code will center around arrays and the str_replace() function. Now arrays are quite simple to use, they are just variables that can hold many different values. They are identified by keys and the keys have values. The way we’re going to do it today is by using:
$array = array("key" => "value");
Then you can access key by doing:
$array[key];
That value is “value”.
Then there’s str_replace();. It is what it looks like. It finds a pattern in a string and replaces it with another pattern. This can be done by: str_replace(pattern, replacement, string).
Now to get the values and keys of the arrays to use in the str_replace() function, I’ll use the array_keys(arrayname) and array_values(arrayname) to get the array keys and values. Now you need an actual array that lists everything to find and everything to replace it with.
$BBCode = array("&" => "&",
"<" => "<",
">" => ">",
"[b]" => "<b>",
"[/b]" => "</b>",
"[i]" => "<i>",
"[/i]" => "</i>",
"[u]" => "<u>",
"[/u]" => "</u>",
"[img]" => "<img src='",
"[/img]" => "'>");
Now to explain everything. Basically it’s an array which looks for things to find (the left side) and what to replace it with (the right side). Note that it will go only one key and value at a time. So when we use the final str_replace() part, it will look kinda like…
$BBCode = array("&" => "&",
"<" => "<",
">" => ">",
"[b]" => "<b>",
"[/b]" => "</b>",
"[i]" => "<i>",
"[/i]" => "</i>",
"[u]" => "<u>",
"[/u]" => "</u>",
"[img]" => "<img src='",
"[/img]" => "'>");
$text = "This is bold text";
$parsedtext = str_replace(array_keys($BBCode), array_values($BBCode), $text);
Now if we really want to turn it into a function, we could do this:
function BBCode($text){
$BBCode = array("&" => "&",
"<" => "<",
">" => ">",
"[b]" => "<b>",
"[/b]" => "</b>",
"[i]" => "<i>",
"[/i]" => "</i>",
"[u]" => "<u>",
"[/u]" => "</u>",
"[img]" => "<img src='",
"[/img]" => "'>");
$parsedtext = str_replace(array_keys($BBCode), array_values($BBCode), $text);
return $parsedtext;
}
$text = "[b]This is bold text[/b]
And there’s a finished function! I’ll do a more advanced tutorial covering how to use urls and emails later.
*Note to everyone! Remove the asterisk unless you want to use the asterisk in the BBCode.
Nice tutorial, but How would I add a [code] and [/code] to that?
by Josh