Search code examples
phptagshtml-escape-characters

Is there a PHP function to htmlspecialchars() everything except for certain tags?


It would be nice if I could call my_escape($text, '<p><b><i>') that escapes everything except all <p>, <b> and <i> tags. I'm looking for a generic solution where I can specify an arbitrary set of tags. Does this exist? If not what's the best approach to implement it?


Solution

  • in htmlspecialchars function it converts html tags to

    & to &amp;
    " to &quot;
    ' to &#039;
    < to &lt;
    > to &gt;
    

    after convert you can do reverse to decode

    <?php
    $test="<p><b><a>Test</b></a></p>";
    
    $test = htmlspecialchars($test);
    
    $test = str_replace("&lt;p&gt;", "<p>", $test);
    $test = str_replace("&lt;i&gt;", "<i>", $test);
    $test = str_replace("&lt;b&gt;", "<b>", $test);
    $test = str_replace("&lt;/b&gt;", "</b>", $test);
    $test = str_replace("&lt;/i&gt;", "</i>", $test);
    $test = str_replace("&lt;/p&gt;", "</p>", $test);
    
    echo $test;
    ?>