我正在尝试编码网站当前的RFC 3986标准并使用此功能:
function getUrl() {
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
$url .= $_SERVER["REQUEST_URI"];
$entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
$replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
return str_replace($entities, $replacements, urlencode($url));
}
添加的网址:http://localhost/test/test-countdown/?city=hayden&eventdate=20160301
返回:http://localhost/test/test-countdown/?city=hayden&eventdate=20160301
未使用//
和&
替换
答案 0 :(得分:1)
虽然规范的解决方案是简单地使用{3}}作为fusion3k说的,但值得注意的是,在推出自己的解决方案时,您应该:
-_.~
之一。代码:
function encode($str) {
return preg_replace_callback(
'/[^\w\-_.~]/',
function($a){ return sprintf("%%%02x", ord($a[0])); },
$str
);
}
var_dump(encode('http://localhost/test/test-countdown/?city=hayden&eventdate=20160301'));
结果:
string(88) "http%3a%2f%2flocalhost%2ftest%2ftest-countdown%2f%3fcity%3dhayden%26eventdate%3d20160301"
答案 1 :(得分:0)
如果您想要以这种格式编码网址(不是网站):
http%3A%2F%2Flocalhost%2Ftest%2Ftest-countdown%2F%3Fcity%3Dhayden%26eventdate%3D20160301
使用内置的php函数rawurlencode( $url )
。
答案 2 :(得分:0)
其他人已经提到过rawurlencode(),但你的代码的问题在于你的数组已经倒退了。
像这样切换你的数组:
function getUrl() {
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
$url .= $_SERVER["REQUEST_URI"];
$entities = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
$replacements = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
return str_replace($entities, $replacements, urlencode($url));
}