2.10. BBCode

Our forum currently uses a plain HTML textarea box to allow a user to submit his or her post and filters out HTML characters using htmlspecialchars() before display for security purposes. In effect, users may only post plain text messages. There are different options available if you wanted to allow users to format their messages — you could remove filtering with htmlspecialchars() and replace the input field with a JavaScript powered rich text editor (I'll show you this in Chapter 10) or you could allow the user to enter special BBCode markup tags.

BBCode (short for Bullet Board Code) is a markup language similar to HTML. While not standardized like HTML, it is in widespread use in many forum applications. You would accept a post marked-up with BBCode tags and then translate them into a subset of allowed HTML tags before displaying it.

Here is some code written to convert BBCode-formatted text to HTML, which I've saved as lib/BBCode.php:

<?php // Class to format text marked up with BBCode tags to HTML-- see // http://www.phpbb.com/community/faq.php?mode=bbcode for more information. Class BBCode { // private method to replace BBCode tags with suitable HTML private static function _format_bbcode($string) { // use regular expression to identify and break apart BBCode tags while (preg_match('|\[([a-z]+)=?(.*?)\](.*?)\[/\1\]|', $string, $part, PREG_OFFSET_CAPTURE)) { $part[2][0] = str_replace('"', "", $part[2][0]); $part[2][0] = str_replace("'", "", $part[2][0]); $part[3][0] ...

Get PHP and MySQL®: Create-Modify-Reuse now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.