PHP 等效于 javascript escape/unescape
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15534674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP equivalent for javascript escape/unescape
提问by chubbyk
Let's say I have a string: something
假设我有一个字符串:某物
When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67
当我在 JS 中转义它时,我得到了这个:%73%6F%6D%65%74%68%69%6E%67
so I can use this code in JS to decode it:
所以我可以在 JS 中使用这段代码来解码它:
document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));
I need the escape function in PHP which will do the same (will encode somethingto : %73%6F%6D%65%74%68%69%6E%67)
我需要 PHP 中的转义函数,它会做同样的事情(将一些东西编码为:%73%6F%6D%65%74%68%69%6E%67)
How to do that ?
怎么做 ?
回答by i--
PHP:
PHP:
rawurlencode("your funky string");
JS:
JS:
decodeURIComponent('your%20funky%20string');
decodeURIComponent('你的%20funky%20string');
Don't use escapeas it is being deprecated.
不要使用,escape因为它已被弃用。
回答by Roger Gajraj
rawurldecode('%73%6F%6D%65%74%68%69%6E%67');
回答by eyecatchUp
Some clarification first:
先做一些澄清:
Let's say I have a string: something
When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67
假设我有一个字符串:某物
当我在 JS 中转义它时我得到这个:%73%6F%6D%65%74%68%69%6E%67
That's wrong. (Btw, the JS escape()function is deprecated. You should use encodeURIComponent()instead!)
那是错误的。(顺便说一句,escape()不推荐使用JS函数。您应该使用它encodeURIComponent()!)
so I can use this code in JS to decode it: document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));
所以我可以在 JS 中使用这段代码来解码它: document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));
Yep, this will write "something"to the document (as escape(), also unescape()is deprecated; use decodeURIComponent()instead).
是的,这会将“某些东西”写入文档(因为escape(),也unescape()已弃用;decodeURIComponent()改为使用)。
To your question:
对于你的问题:
I need the [snip] function in PHP which [snip] encode somethingto %73%6F%6D%65%74%68%69%6E%67
我需要 PHP 中的 [snip] 函数 [snip] 将某些内容编码为%73%6F%6D%65%74%68%69%6E%67
What you're looking for is the hexadecimal representation of charachters. So, to get the string "%73%6F%6D%65%74%68%69%6E%67"from the string "something", you would need:
您正在寻找的是字符的十六进制表示。因此,要从字符串"something" 中获取字符串"%73%6F%6D%65%74%68%69%6E%67 ",您需要:
<?php
function stringToHex($string) {
$hexString = '';
for ($i=0; $i < strlen($string); $i++) {
$hexString .= '%' . bin2hex($string[$i]);
}
return $hexString;
}
$hexString = stringToHex('something');
echo strtoupper($hexString); // %73%6F%6D%65%74%68%69%6E%67
Backwards:
向后:
function hexToString($hexString) {
return pack("H*" , str_replace('%', '', $hexString));
}
$string = hexToString('%73%6F%6D%65%74%68%69%6E%67');
echo $string; // something

