Search code examples
htmlhtmlspecialchars

htmlspecialchars(); don't work


When I use "htmlspecialchars" in this code:

<?php
$test = htmlspecialchars("<a>w3s.com</a>");
echo $test;
?>

I want see HTML entites, such as:

&quot;&gt;&lt;script&gt;alert - for example.

But I see this:

<a>w3s.com</a>

And in browser HTML markup doesn't display HTML entites. Please help. Thank (Sorry if my sentense building of words building are spooky.)


Solution

  • If you want the browser to display the special characters you should write something like this:

    <?php
    $test = htmlspecialchars(str_replace(array("'", "\""), "", 
        htmlspecialchars("<a>w3s.com</a>")));
    echo $test;
    ?>
    

    Output: &lt;a&gt;w3s.com&lt;/a&gt;

    This way you escape the special characters in order to let the browser draw them

    If you want to see HTML entities rendered by the browser just write the HTML code, like this:

    <?php
    $test = '<a href="http://w3s.com">Enter here</a>';
    echo $test;
    ?>
    

    Output: Enter here

    I think you forgot to put the href attribute and so it didn't display it as an anchor. For more info visit this w3schools' article