實現 PHP urlencode() 的編碼方式

1 篇文章 / 0 new
author
實現 PHP urlencode() 的編碼方式

原是為了用來克服 php/windows 下 unicode檔名問題, 但發現當連結使用 urlencode編碼運作時, 瀏覽器又會自動 decode成原編碼, 所以想用此法解決 unicode filename 是不可行. 需要改用其他方式.

function php_urlEncode(srcStr) {
    var output = '';
    var x = 0;
    srcStr = utf16to8(srcStr.toString());
    var regex = /(^[a-zA-Z0-9-_.]*)/;
    while (x < srcStr.length)
    {
        var match = regex.exec(srcStr.substr(x));
        if (match != null && match.length > 1 && match[1] != '')
        {
            output += match[1];
            x += match[1].length;
        }
        else
        {
            if (srcStr[x] == ' ')
                output += '+';
            else
            {
                var charCode = srcStr.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
            }
            x++;
        }
    }
    function utf16to8(str)
    {
        var out, i, len, c;
        out = "";
        len = str.length;
        for(i = 0; i < len; i++)
        {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F))
            {
                out += str.charAt(i);
            }
            else if (c > 0x07FF)
            {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
            }
            else
            {
                out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
            }
        }
        return out;
    }
    return output;
}
Free Web Hosting