How can the preg_replace() function in PHP be used to handle multiple occurrences of BBCode formatting?

When using preg_replace() in PHP to handle multiple occurrences of BBCode formatting, you can use the "/g" modifier to replace all occurrences of a pattern instead of just the first one. This allows you to properly handle multiple instances of BBCode tags in a string.

// Sample BBCode string
$bbcode = "[b]Hello[/b] [i]World[/i] [b]Foo[/b] [b]Bar[/b]";

// Replace [b] tags with <strong> tags
$bbcode = preg_replace("/\[b\](.*?)\[\/b\]/g", "<strong>$1</strong>", $bbcode);

// Replace [i] tags with <em> tags
$bbcode = preg_replace("/\[i\](.*?)\[\/i\]/g", "<em>$1</em>", $bbcode);

echo $bbcode;