htmladdslashes

How do I escape characters in href of anchor tag


I want to escape three characters these are

  1. single quote (')
  2. double quote (")
  3. backslash ()

my href value is test.html?key="test' me'"&event=3

I want to fix it as we do in php by calling addslashes function

<a href="test.html?key="test' me'"&event=3">test</a>

NOTE: I need a dynamic way of doing it


Solution

  • The PHP function to take data and generate a properly encoded query string is http_build_query. You can then put it in a URL and then encode that using htmlspecialchars to insert it in a document.

    <?php
    
        $base = "test.html";
        $query_data = Array(
            "key" => "\"test' me'\"",
            "event" => 3
        );
        $url = $base . "?" . http_build_query($query_data);
        $html_safe_url = htmlspecialchars($url);
    ?>
    
        <a href="<?= $html_safe_url ?>">test</a>