我试图发送一个包含与符号的字符串的GET消息,不知道如何在URL中转义与符号。

例子:

http://www.example.com?candy_name=M&M
result => candy_name = M

我还试过:

http://www.example.com?candy_name=M\&M
result => candy_name = M\\

我手动使用url,所以我只需要正确的字符。

我不能使用任何库。怎样才能做到呢?


当前回答

如果有人想在PHP中使用它,这可能会有所帮助

$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);

其他回答

我想对Blender的解决方案添加一个小小的评论。

您可以执行以下操作:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');

输出:

http://example.com?candy_name=M%26M

这样做的好处是,它不仅适用于&,而且适用于任何特殊字符。

例如:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')

输出:

"http://example.com?candy_name=M%26M%3F%3E%3C"

您可以使用encodeURIComponent函数传递参数,这样就不必担心传递任何特殊字符。

data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos&param2="+encodeURIComponent(someValue)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

如果你不能使用任何库来编码值, http://www.urlencoder.org/或http://www.urlencode-urldecode.com/或…

只需输入你的值“M&M”,而不是完整的URL;-)

如果有人想在PHP中使用它,这可能会有所帮助

$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);

这不仅适用于url中的&号,还适用于所有保留字符。其中包括:

 # $ & + ,  / : ; = ? @ [ ]

其思想与在HTML文档中编码&相同,但是上下文除了在HTML文档中之外,还更改为在URI中。因此,百分比编码可以防止在两个上下文中进行解析的问题。

当你需要把一个URL放到另一个URL里面的时候,这个就会派上用场了。例如,如果你想在Twitter上发布一个状态:

http://www.twitter.com/intent/tweet?status=What%27s%20up%2C%20StackOverflow%3F(http%3A%2F%2Fwww.stackoverflow.com)

在我的Tweet中有很多保留字符,即?'():/,所以我对状态URL参数的整个值进行了编码。这在使用具有消息体或主题的mailto:链接时也很有帮助,因为您需要对消息体和主题参数进行编码,以保持换行符、&号等不变。

When a character from the reserved set (a "reserved character") has special meaning (a "reserved purpose") in a certain context, and a URI scheme says that it is necessary to use that character for some other purpose, then the character must be percent-encoded. Percent-encoding a reserved character involves converting the character to its corresponding byte value in ASCII and then representing that value as a pair of hexadecimal digits. The digits, preceded by a percent sign ("%") which is used as an escape character, are then used in the URI in place of the reserved character. (For a non-ASCII character, it is typically converted to its byte sequence in UTF-8, and then each byte value is represented as above.) The reserved character "/", for example, if used in the "path" component of a URI, has the special meaning of being a delimiter between path segments. If, according to a given URI scheme, "/" needs to be in a path segment, then the three characters "%2F" or "%2f" must be used in the segment instead of a raw "/".

http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters