phphtml-entitieshtmlspecialchars

PHP htmlspecialchars() or htmlentities() with exception


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>


Solution

  • 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('/&lt;(\/?(strong|b|i|em|br))&gt;/', '<$1>', $encoded_string);
    
    echo($encoded_string); 
    //outputs: &lt;p&gt;<strong>A <i>test</i> string with a &lt;a href=&quot;#&quot;&gt;Test link&lt;/a&gt;</strong>&lt;/p&gt;
    

    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.