What are the best practices for filtering text using regular expressions in PHP, specifically in the context of BBCode examples?

When filtering text using regular expressions in PHP, specifically in the context of BBCode examples, it is important to properly sanitize the input to prevent any potential security vulnerabilities such as cross-site scripting (XSS) attacks. One common approach is to use regular expressions to match and replace specific BBCode tags with their corresponding HTML equivalents. This helps ensure that only safe and valid HTML content is displayed to users.

function filterBBCode($input) {
    // Define an array of BBCode tags and their corresponding HTML replacements
    $bbcodeTags = array(
        '/\[b\](.*?)\[\/b\]/is' => '<strong>$1</strong>',
        '/\[i\](.*?)\[\/i\]/is' => '<em>$1</em>',
        '/\[url\](.*?)\[\/url\]/is' => '<a href="$1">$1</a>'
    );

    // Loop through each BBCode tag and replace it with its HTML equivalent
    foreach ($bbcodeTags as $bbcode => $html) {
        $input = preg_replace($bbcode, $html, $input);
    }

    return $input;
}

// Example usage
$input = "[b]Hello[/b] [i]world[/i] [url]https://example.com[/url]";
$output = filterBBCode($input);
echo $output;