What are some best practices for implementing BBCode in PHP to ensure efficient and secure text formatting?

When implementing BBCode in PHP, it is important to sanitize user input to prevent cross-site scripting attacks and ensure the security of your application. One way to achieve this is by using PHP's built-in functions like htmlspecialchars() to encode special characters. Additionally, you can create a whitelist of allowed BBCode tags and attributes to restrict user input to only safe elements.

// Function to sanitize user input for BBCode
function sanitizeBBCode($input) {
    // Encode special characters
    $input = htmlspecialchars($input, ENT_QUOTES);

    // Whitelist of allowed BBCode tags and attributes
    $input = preg_replace('/\[b\](.*?)\[\/b\]/is', '<strong>$1</strong>', $input);
    $input = preg_replace('/\[i\](.*?)\[\/i\]/is', '<em>$1</em>', $input);
    // Add more allowed BBCode tags as needed

    return $input;
}

// Example usage
$userInput = '[b]Hello[/b] [i]world[/i]';
$sanitizedInput = sanitizeBBCode($userInput);
echo $sanitizedInput;