What potential issue can arise when using preg_replace for replacing nested BBCode tags in PHP?

When using preg_replace to replace nested BBCode tags in PHP, a potential issue that can arise is that the regular expression may not handle nested tags correctly, leading to unexpected results or errors. To solve this issue, you can use a recursive approach by repeatedly applying preg_replace until no more nested tags are found.

function replaceNestedBBCode($text) {
    $pattern = '/\[(\w+)(?:=[^\]]+)?\](?:(?R)|.)*?\[\/\1\]/';
    
    while (preg_match($pattern, $text)) {
        $text = preg_replace_callback($pattern, function($matches) {
            return preg_replace($pattern, '', $matches[0]);
        }, $text);
    }
    
    return $text;
}

$text = "[b][i]Nested BBCode[/i][/b]";
echo replaceNestedBBCode($text);