encodeURI() in PHP?

2020-01-26 08:22发布

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

标签: php url
2条回答
smile是对你的礼貌
2楼-- · 2020-01-26 09:08

Here's an alternate version based on MDN spec:

function encodeURI($uri)
{
    return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) {
        return sprintf('%%%02X', ord($m[0]));
    }, $uri);
}
查看更多
Anthone
3楼-- · 2020-01-26 09:13

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.

查看更多
登录 后发表回答