[WD:PHP] Parsing Formatting (BBcode) Tags
Ever work on a project where you need to create tags for user input? You might have realized that using str_replace() doesn't really cut it very well.
Using the above code presents a few problems. What if your user used [B] instead of [b]? What if they forgot the closing [/b] tag? Then the rest of the text on the page will be bold. You could have a series of checks and multiple replaces. Loops and ifs, the whole works. But using a regular expression would be much easier.
$text = str_replace("[b]", "<b>", $text);
It isn't my aim here to teach all about regular expressions. I think that would give us both a headache. But I am going to show how to do some simple and complex tags.
So what about that bold tag?
The first parameter is our search pattern: /\[b\](.*)\[\/b\]/siU
$text = preg_replace("/\[b\](.*)\[\/b\]/siU", "<b>\\1</b>", $text);
Our pattern is incased with forward slashes (/pattern/). The characters [ ] / must all be escaped with the escape character (/).
(.*) is a wildcard. When we use it, we're telling the function that any text can be between the two tags.
The second parameter is our replacement. The \\# stands for wildcard placements. Since we only have one wildcard, we just use \\1.
If we had two wildcards, we would use both \\1, and \\2 to refer to the text.
The first two parameters of the preg_replace() function can be arrays, so we can do this:
$tags = array("/\[b\](.*)\[\/b\]/siU", "/\[i\](.*)\[\/i\]/siU", "/\[u\](.*)\[\/u\]/siU");
$html = array("<b>\\1</b>", "<i>\\1</i>", "<u>\\1</u>");
$text = preg_replace($tags, $html, $text);
When we want to do a URL, COLOR, or FONT tag, we would do those like this:
Replacement: <htmltag param=“\\1”>\\2</htmltag>
It's that simple.
NOTE: the siU at the end of each pattern are known as Pattern Modifiers. For explanations, follow this link. For more information on Pattern Syntax, go here