In PHP development, what are some best practices for creating custom parsers or functions for text formatting like BB-Codes?

When creating custom parsers or functions for text formatting like BB-Codes in PHP development, it is important to use regular expressions to efficiently parse and replace the desired formatting tags. Additionally, it is recommended to sanitize user input to prevent any potential security vulnerabilities. Lastly, consider creating a reusable function or class to handle the parsing logic for better code organization and maintainability.

function parseBBCode($text) {
    // Define the BB-Codes and their corresponding HTML tags
    $bbCodes = [
        '/\[b\](.*?)\[\/b\]/is' => '<strong>$1</strong>',
        '/\[i\](.*?)\[\/i\]/is' => '<em>$1</em>',
        '/\[url\](.*?)\[\/url\]/is' => '<a href="$1">$1</a>'
    ];

    // Loop through each BB-Code and replace it with the corresponding HTML tag
    foreach ($bbCodes as $bbCode => $htmlTag) {
        $text = preg_replace($bbCode, $htmlTag, $text);
    }

    return $text;
}

// Usage example
$text = "[b]Hello[/b] [i]world[/i]! Visit my website at [url]https://example.com[/url].";
echo parseBBCode($text);