PHP 中的 encodeURI() ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4929584/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:17:31  来源:igfitidea点击:

encodeURI() in PHP?

phpurl

提问by fatalSc

Is there some encodeURI() function in PHP that does not encode: ~!@#$&*()=:/,;?+'?

PHP 中是否有一些 encodeURI() 函数不编码:~!@#$&*()=:/,;?+'

回答by commonpike

I'm using this now

我现在在用这个

function encodeURI($url) {
    // http://php.net/manual/en/function.rawurlencode.php
    // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
    $unescaped = array(
        '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~',
        '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'
    );
    $reserved = array(
        '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':',
        '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$'
    );
    $score = array(
        '%23'=>'#'
    );
    return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score));

}

It basically rawurlencodes everything, and then decodes a few things back (as Zanlok suggested in his comment). This should conform to the Mozilla specs of encodeURI.

它基本上对所有内容进行原始编码,然后将一些内容解码回来(正如 Zanlok 在他的评论中所建议的那样)。这应该符合 encodeURI 的 Mozilla 规范。

回答by Paulo Freitas

Here's an alternate version based on ECMA-262 spec:

这是基于ECMA-262 规范的替代版本:

function encodeURI($uri)
{
    return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) {
        return sprintf('%%%02X', ord($m[0]));
    }, $uri);
}