【发布时间】:2011-09-04 15:43:29
【问题描述】:
它们的区别在于PHP的urlencode用+而不是%20编码空格?
对两种语言执行相同操作的函数有哪些?
【问题讨论】:
标签: php javascript urlencode
它们的区别在于PHP的urlencode用+而不是%20编码空格?
对两种语言执行相同操作的函数有哪些?
【问题讨论】:
标签: php javascript urlencode
在 PHP 中使用 rawurlencode 代替 urlencode。
【讨论】:
rawurlencode 是用于 /.../ 而 urlencode 是用于 /?....
rawurlencode 和 encodeURIComponent 产生相同的输出。
在 php 自己的文档 rawurlencode 上关注此链接
rawurlencode 可以解决问题,链接仅供参考。
【讨论】:
实际上,即使使用 JavaScript encodeURIComponent 和 PHP rawurlencode,它们也不完全相同,例如 '(' 字符,JavaScript encodeURIComponent 不会将其转换但 PHP rawurlencode 会将其转换为 %28。经过一些实验和提示其他诸如这个问题another Stackoverflow question。
我找到了终极解决方案here。
您需要做的就是使用添加以下代码
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
例如,它们现在将完全相同相同
fixedEncodeURIComponent(yourUrl) (JavaScript) = (PHP) rawurlencode(yourUrl)
解码没问题,JavaScript 可以使用 decodeURIComponent(),PHP 可以使用 rawurldecode
【讨论】:
我在rawurlencode() 和encodeURIComponent() 之间遇到了同样的问题。对我来说不同的是,直到在大量源文件中使用 encodeURIComponent() 后我才发现问题,因此返回修复并更改它们,然后重新测试所有内容不是一个选项。
幸运的是,JS 使您能够通过为新函数分配相同的名称来“劫持”内置函数。因此,您只需对 Phantom1412 的代码稍作修改即可更改 encodeURIComponent() 的行为,而无需重新编码。
在您的代码对encodeURIComponent() 进行任何调用之前,只需将此脚本放在您的页面中:
var encodeURIComponentOld = encodeURIComponent;
encodeURIComponent = function(str) {
return encodeURIComponentOld(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
};
【讨论】: