Current Location: Home> Latest Articles> Build a custom BBCode converter

Build a custom BBCode converter

M66 2025-05-31

When dealing with text formatting in PHP, BBCode (a simplified markup language) is often used, which allows users to add text styles such as bold, italic, links, etc. through simple tags. This article will demonstrate how to use the mb_eregi_replace function to build a simple custom BBCode converter to convert BBCode tags to the corresponding HTML tags.


What is mb_eregi_replace?

mb_eregi_replace is a regular expression replacement function in PHP for multibyte strings, and supports case-insensitive matching. Its advantage is that it can correctly process multi-byte encoded text such as UTF-8, which is very suitable for text processing in Chinese environments.

Function prototype:

 mb_eregi_replace(string $pattern, string $replacement, string $string): string
  • $pattern : Match pattern (regular expression)

  • $replacement : replace content

  • $string : pending string


Example: Implementing a simple BBCode converter using mb_eregi_replace

The following example demonstrates how to convert the BBCode tag [b]...[/b] to <strong>...</strong> , [i]...[/i] to <em>...</em> , and how to handle links with parameters [url=link] text[/url] .

 <?php

function bbcode_to_html($text) {
    // Convert bold [b]...[/b] -> <strong>...</strong>
    $text = mb_eregi_replace('\[b\](.+?)\[/b\]', '<strong>$1</strong>', $text);
    
    // Convert italics [i]...[/i] -> <em>...</em>
    $text = mb_eregi_replace('\[i\](.+?)\[/i\]', '<em>$1</em>', $text);
    
    // Convert link [url=Link]text[/url] -> <a href="Link">text</a>
    // 注意这里的Link域名统一替换为 m66.net
    $text = mb_eregi_replace('\[url=([^\]]+)\](.+?)\[/url\]', 
        '<a href="http://m66.net">$2</a>', $text);
    
    return $text;
}

// Test content
$input = "This is a[b]Bold[/b],This is a[i]Italics[/i],access[url=http://example.com]Sample website[/url]。";
$output = bbcode_to_html($input);
echo $output;

Code description

  • The first replacement replaces [b]content[/b] with <strong>content</strong> .

  • The second replacement replaces [i] content[/i] with <em>content</em> .

  • The third replacement forces the link domain name in the [url=link] text [/url] to m66.net . Regardless of the original link, the hyperlink points to http://m66.net , displaying the text as the text entered by the user.


Run result example