Regular expressions and all things nice
By Jonathan Street
First of all we want to start our function. I've called it output_post. It will take just one variable, $post, this will be the bbCode formatted text.
First of all a couple of house keeping tasks. The whole reason for allowing our users to use bbCode is so that they don't use html. The first thing we do therefore is make sure html won't work using htmlspecialchars. htmlspecialchars converts the characters necessary for html markup to their character entity references. Secondly we chop the post. This gets rid of any whitespace characters at the end of the visitors submission.
Next we need to tackle the code tag. Unlike the other tags we don't want any other tags working when nested within code tags. The whole point of the code tags is that it is displayed exactly as typed. Because of this it can't be treated in the same way as the other tags. As you'll see later we're able to deal with all the other tags with just one function. Code needs to be treated seperately.
What we do here is search through the visitors' submission looking for text that matches the regular expression "/\[code\](.+?)\[\/code\]/s" (I'll come back to the regular expression) using preg_replace_callback, when we find it we send this text to the function convert_for_html. The simplest way to stop bbCode tags within code tags being converted later is to change them to something else. For this we substitute the [ and ] characters with their character entity references, [ and ], using the str_replace function. To anybody viewing the submission it will look just the same but it won't be converted by our code. We then put the text between the code tags in a table and re-insert it into the post.
Before we take a closer look at that regular expression it will make more sense to throw the other bbCode tags into the mix. They're all made in the same way.
This site best viewed in a W3C standard browser at 800*600 or higher
Site design by Red Squirrel | Contact
© Copyright 2021 Ryan Auclair/IceTeks, All rights reserved