What is the best practice for handling bb codes conversion in PHP to avoid errors or unexpected behavior?

When handling BB codes conversion in PHP, it is best practice to use regular expressions to match and replace the BB codes with their corresponding HTML tags. This approach ensures that the conversion is accurate and efficient, avoiding errors or unexpected behavior. Additionally, using a function to encapsulate the conversion logic can make the code more modular and reusable.

function convertBBCodeToHTML($text) {
    $bbCodes = [
        '/\[b\](.*?)\[\/b\]/is' => '<strong>$1</strong>',
        '/\[i\](.*?)\[\/i\]/is' => '<em>$1</em>',
        '/\[url\](.*?)\[\/url\]/is' => '<a href="$1">$1</a>'
    ];

    foreach ($bbCodes as $pattern => $replacement) {
        $text = preg_replace($pattern, $replacement, $text);
    }

    return $text;
}

// Example usage
$bbCodeText = "[b]Hello[/b] [i]World[/i] [url]https://www.example.com[/url]";
$htmlText = convertBBCodeToHTML($bbCodeText);
echo $htmlText;