What are the best practices for converting BBCode to HTML or CSS in PHP?

When converting BBCode to HTML or CSS in PHP, it is important to use regular expressions to match and replace the BBCode tags with their corresponding HTML or CSS equivalents. Additionally, it is recommended to sanitize the input to prevent any potential security vulnerabilities.

function bbcodeToHtml($bbcode) {
    $bbcode = htmlspecialchars($bbcode); // Sanitize input
    $bbcode = preg_replace('/\[b\](.*?)\[\/b\]/', '<strong>$1</strong>', $bbcode); // Convert [b] tags to <strong>
    $bbcode = preg_replace('/\[i\](.*?)\[\/i\]/', '<em>$1</em>', $bbcode); // Convert [i] tags to <em>
    $bbcode = preg_replace('/\[url\](.*?)\[\/url\]/', '<a href="$1">$1</a>', $bbcode); // Convert [url] tags to <a>
    
    return $bbcode;
}

$bbcode = "[b]Bold text[/b] [i]Italic text[/i] [url]https://www.example.com[/url]";
$html = bbcodeToHtml($bbcode);
echo $html;