Search code examples
phpsqltextareacharacter-codes

Prevent HTML character codes from being rendered in textarea


Is it possible to display HTML character codes stored in a text field in SQL to a textarea without rendering them as their appropriate character? i wasnt & to show up as & (the way it's stored in the table). Or is their a way I should be storing the HTML so I won't need to worry about this?

(site is using PHP)


Solution

  • In PHP you can use the function htmlspecialchars ( http://php.net/manual/en/function.htmlspecialchars.php ):

    <?php
    $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
    echo $new;
    ?>
    

    and it will render:

    &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
    

    if you want decode them back you just use the function htmlspecialchars_decode

    <?php
    $str = '<p>this -&gt; &quot;</p>';
    
    echo htmlspecialchars_decode($str);
    
    // note that here the quotes aren't converted
    echo htmlspecialchars_decode($str, ENT_NOQUOTES);
    ?>