url编码统一方案,js中encodeURIComponent和PHP中rawurlencode
RFC 3986 标准,简单讲就是规定了如下:除了 数字 + 字母 + -_.~ 不会被转义,其他字符都会被以百分号(%)后跟两位十六进制数 %{hex} 的方式进行转义。
JS中encodeURIComponent使用这个标准,PHP中rawurlencode也使用这个标准.
js的encodeURIComponent不转义的字符A-Z a-z 0-9 - _ . ! ~ * ' ( )
php不专义的是A-Z a-z 0-9 - _ . ~
php中
$arr = [ '%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')', ]; $str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; $strPhp = rawurlencode($str); $strEncode = str_replace(array_keys($arr), array_values($arr), $strPhp); echo $strEncode;
js中
let str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
        document.write(encodeURIComponent(str));
目前结果一致,待完善中.
方式一完整示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> <?php $arr = [ '%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')', ]; $str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; $strPhp = rawurlencode($str); $strEncode = str_replace(array_keys($arr), array_values($arr), $strPhp); echo $strEncode; ?> <br> <script type="text/javascript"> let str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; document.write(encodeURIComponent(str)); </script> </body> </html>
  -------------------------------------------------------------------------------------------------------------
另一种方式让js编码!'()*
function customURLEncode(url) { return encodeURIComponent(url).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
方式二完整示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> <?php $str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; $strPhp = rawurlencode($str); echo $str.'<br>'; echo $strPhp; ?> <br> <script type="text/javascript"> let str = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; let strjs = customURLEncode(str); document.write(strjs); function customURLEncode(url) { return encodeURIComponent(url).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); } function customURLDecode(encodedUrl) { return decodeURIComponent(encodedUrl.replace(/%(?![0-9a-fA-F]{2})/g, function(match) { return match === '%' ? '%' : String.fromCharCode(parseInt(match.substr(1), 16)); })); } document.write('<br>'); document.write(customURLDecode(strjs)); </script> </body> </html>

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号