How do I escape characters in href of anchor tag

允我心安 提交于 2019-12-08 09:58:43

问题


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


回答1:


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:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/37695320/how-do-i-escape-characters-in-href-of-anchor-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!