What are the potential pitfalls of using preg_replace() to replace BBCode with HTML in PHP?

One potential pitfall of using preg_replace() to replace BBCode with HTML in PHP is that it may not handle nested BBCode tags correctly, leading to unexpected results or errors in the output. To solve this issue, you can use a recursive approach to replace nested BBCode tags with HTML.

function replaceBBCode($text) {
    $bbcodePattern = "/\[([a-z]+)(?:=(.*?)|)\](.*?)\[\/\\1\]/is";
    
    while (preg_match($bbcodePattern, $text)) {
        $text = preg_replace_callback($bbcodePattern, function($matches) {
            return "<{$matches[1]}>".replaceBBCode($matches[3])."</{$matches[1]}>";
        }, $text);
    }
    
    return $text;
}

$originalText = "[b]Bold text with [i]italic[/i] inside[/b]";
$htmlText = replaceBBCode($originalText);
echo $htmlText;