Convert BBCode to HTML in PHP
Learn how to parse BBCode tags and smileys into HTML using PHP regex, with a reusable function covering bold, italic, links, images, lists, and code blocks.
BBCode to HTML Conversion
BBCode (Bulletin Board Code) is a lightweight markup language used in forums and message boards. Converting BBCode to HTML lets you render user-generated content safely on the web. This tutorial shows how to build a reusable PHP function that parses common BBCode tags and smiley codes into proper HTML.
Basic BBCode Parser Function
function bbcodeToHtml($text) { // Escape HTML first to prevent XSS $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); // BBCode patterns => HTML replacements $patterns = [ '/\[b\](.*?)\[\/b\]/s' => '<strong>$1</strong>', '/\[i\](.*?)\[\/i\]/s' => '<em>$1</em>', '/\[u\](.*?)\[\/u\]/s' => '<u>$1</u>', '/\[s\](.*?)\[\/s\]/s' => '<del>$1</del>', '/\[url=(.*?)\](.*?)\[\/url\]/s' => '<a href="$1">$2</a>', '/\[url\](.*?)\[\/url\]/s' => '<a href="$1">$1</a>', '/\[img\](.*?)\[\/img\]/s' => '<img src="$1" alt="">', '/\[color=(.*?)\](.*?)\[\/color\]/s' => '<span style="color:$1">$2</span>', '/\[size=(.*?)\](.*?)\[\/size\]/s' => '<span style="font-size:$1">$2</span>', '/\[code\](.*?)\[\/code\]/s' => '<pre><code>$1</code></pre>', '/\[quote\](.*?)\[\/quote\]/s' => '<blockquote>$1</blockquote>', ]; foreach ($patterns as $pattern => $replace) { $text = preg_replace($pattern, $replace, $text); } // Convert newlines $text = nl2br($text); return $text; }
Adding List Support
BBCode lists use [list] and [*] tags. Add these patterns to handle ordered and unordered lists:
// Unordered list '/\[list\](.*?)\[\/list\]/s' => '<ul>$1</ul>', // Ordered list '/\[list=1\](.*?)\[\/list\]/s' => '<ol>$1</ol>', // List items '/\[\*\](.*?)(?=\[\*\]|\[\/list\])/s' => '<li>$1</li>',
Smiley Code Replacement
Forums often support text smileys like :) or :D. You can map these to emoji or image tags:
function convertSmileys($text) { $smileys = [ ':)' => '🙂', ':D' => '😀', ':(' => '🙁', ';)' => '😉', ':P' => '😋', ':o' => '😮', ]; return str_replace( array_keys($smileys), array_values($smileys), $text ); }
Security Considerations
Always call htmlspecialchars() before applying BBCode replacements. This prevents XSS attacks where users inject malicious JavaScript through BBCode attributes. For the [url] tag, validate that the href starts with http:// or https:// to block javascript: protocol attacks.
Complete Usage Example
$bbcode = '[b]Hello[/b] [i]world[/i] :) [url=https://example.com]Click[/url]'; $html = bbcodeToHtml($bbcode); $html = convertSmileys($html); echo $html; // Output: <strong>Hello</strong> <em>world</em> 🙂 <a href="https://example.com">Click</a>
Last updated: 2026 • Browse all courses