How can htmlentities() and html_entity_decode() be effectively used to handle HTML tags within specific BB-Code tags?
When handling HTML tags within specific BB-Code tags, htmlentities() can be used to encode the HTML tags to prevent them from being parsed as actual HTML. Then, html_entity_decode() can be used to decode the encoded HTML tags back to their original form when rendering the content.
// Encode HTML tags within specific BB-Code tags
$content = "[b]This is a <strong>bold</strong> text[/b]";
$content = preg_replace_callback('/\[b\](.*?)\[\/b\]/s', function($matches) {
return '[b]' . htmlentities($matches[1]) . '[/b]';
}, $content);
// Decode HTML tags back when rendering the content
$content = preg_replace_callback('/\[b\](.*?)\[\/b\]/s', function($matches) {
return '<strong>' . html_entity_decode($matches[1]) . '</strong>';
}, $content);
echo $content;