How do I escape characters in href of anchor tag

18.7k views Asked by At

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

3

There are 3 answers

0
Quentin On BEST ANSWER

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>
2
abcdefghiraj On

Encode the Url maybe

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

Check out these url encodings at w3schools

ADDED: var $key ="\"test'\""; var $event = "3"; print '<a href="test.html?key=' . urlencode($key) .'&event=' . urlencode($event) .'">test</a>';

I don't exactly know how php strings escape special characters like " but I suppose \" would work.

0
Lennard Schutter On

You have to URL encode your special characters.

A " would become %22

A ' would become %27

A \ would become %5C

Your anchor would have to be

test.html?key=%22test%27%20me%27%22&event=3

For more information on url encoding go to http://www.w3schools.com/tags/ref_urlencode.asp.