How can preg_replace for bbcodes be better secured in PHP?

To better secure preg_replace for bbcodes in PHP, it is important to use the 'e' modifier carefully, as it can execute arbitrary PHP code. Instead, it is recommended to use preg_replace_callback to safely handle the replacements. This allows you to define a callback function to process the matches and ensure that only safe replacements are made.

// Example of using preg_replace_callback for secure bbcodes replacement
$text = "[b]Bold text[/b] [i]Italic text[/i] [url=http://example.com]Link[/url]";
$bbcodes = [
    '/\[b\](.*?)\[\/b\]/s' => '<strong>$1</strong>',
    '/\[i\](.*?)\[\/i\]/s' => '<em>$1</em>',
    '/\[url=(.*?)\](.*?)\[\/url\]/s' => '<a href="$1">$2</a>'
];

foreach ($bbcodes as $pattern => $replacement) {
    $text = preg_replace_callback($pattern, function($matches) use ($replacement) {
        return preg_replace('/(\$[0-9])/', '\\\\$1', $replacement);
    }, $text);
}

echo $text;