encodeURI() in PHP?

前端 未结 2 1742
孤独总比滥情好
孤独总比滥情好 2020-11-29 07:44

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

2条回答
  •  日久生厌
    2020-11-29 08:07

    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.

    And following MDN, 'if one wishes to follow the more recent RFC3986 for URLs', add

    function fixedEncodeURI($url) {
        return strtr(encodeURI($url),array('%5B'=>'[', '%5D'=>']'));
    }
    

提交回复
热议问题