How can I define an exception for htmlspecialchars()
or htmlentities()
?
I would like to have all special characters converted to be HTML safe except for <strong><b><i><em><br>
Easiest way would be to convert your string with htmlentities
and then use preg_replace to replace back the selected tags:
<?php
$string = '<p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>';
$encoded_string = htmlentities($string);
$encoded_string = preg_replace('/<(\/?(strong|b|i|em|br))>/', '<$1>', $encoded_string);
echo($encoded_string);
//outputs: <p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>
Of course if you want to handle arguments inside the tags as well, then the regex pattern needs some work, although these tags are generally lacking any argument.