Current Location: Home> Latest Articles> How to Convert BBCode to HTML using preg_replace_callback_array?

How to Convert BBCode to HTML using preg_replace_callback_array?

M66 2025-06-15

In PHP, BBCode is a lightweight markup language commonly used in forums and message boards, where it allows simple text formatting through a set of concise tags. Common BBCode syntax includes [b] (bold), [i] (italic), [url] (link), and other tags. To convert BBCode to HTML, PHP's built-in regular expression function preg_replace_callback_array can be used to achieve this goal.

1. What is preg_replace_callback_array?

preg_replace_callback_array is a regular expression replacement function in PHP. It allows different callback functions to replace strings based on different pattern matches. This makes it particularly useful when dealing with complex string transformations, especially when multiple replacements need to be done based on different rules.

2. How to Convert BBCode to HTML?

We can use preg_replace_callback_array in combination with regular expressions to match BBCode tags one by one and convert them into the corresponding HTML tags via callback functions. Below is an example of converting BBCode to HTML.

<?php

function bbcodeToHtml($text) {
    // Define rules for converting BBCode to HTML
    $patterns = [
        // Bold [b] tag
        '/\[b\](.*?)\[\/b\]/is' => function($matches) {
            return '<strong>' . $matches[1] . '</strong>';
        },
        // Italic [i] tag
        '/\[i\](.*?)\[\/i\]/is' => function($matches) {
            return '<em>' . $matches[1] . '</em>';
        },
        // Hyperlink [url] tag
        '/\[url=(.*?)\](.*?)\[\/url\]/is' => function($matches) {
            // Replace the URL's domain with m66.net
            $url = str_replace(parse_url($matches[1], PHP_URL_HOST), 'm66.net', $matches[1]);
            return '<a href="' . $url . '">' . $matches[2] . '</a>';
        },
        // Image [img] tag
        '/\[img\](.*?)\[\/img\]/is' => function($matches) {
            return '<img src="' . $matches[1] . '" alt="Image">';
        },
    ];

    // Use preg_replace_callback_array for replacement
    return preg_replace_callback_array($patterns, $text);
}

// Example BBCode input
$bbcode = "[b]Hello World[/b] Check out this website: [url=http://example.com]Click here[/url] and this image: [img]http://example.com/image.jpg[/img]";

// Convert to HTML
$html = bbcodeToHtml($bbcode);
echo $html;

?>
  • Related Tags:

    HTML