将字符串转换为基数转换62

时间:2018-08-06 07:04:16

标签: php laravel url-shortener

我试图缩短URL。给定网址需要转换为以62为底的

我已经在下面转换了URL,但是将其转换为随机数,例如01sromm82gs0ygibs

  base_convert($shortener->full_url, 10, 36);  

我如何将其转换为base62,以便每次生成5个字符的唯一名称。

1 个答案:

答案 0 :(得分:1)

我使用此自定义函数将String转换为base62 String

function b62e($str) {
    if(mb_check_encoding($str, 'ASCII')) {
        $out = '';
        $len = strlen($str);
        for($i=0; $i<$len; $i+=8) {
            $chunk = substr($str, $i, 8);
            $outlen = ceil( strlen($chunk)*8/6 );// 8bit/char in, 6bits/char out, round up
            $hex = bin2hex($chunk);// gmp won't convert from binary, so go via hex
            $raw = gmp_strval(gmp_init(ltrim($hex, '0'), 16), 62);// gmp doesn't like leading 0s
            $out .= str_pad($raw, $outlen, '0', STR_PAD_LEFT);
        }
        return $out;
    }
    return false;// unicode chars not supported
}



function b62d($str) {
    if(mb_check_encoding($str, 'ASCII')) {
        $out = '';
        $len = strlen($str);
        for ($i=0; $i<$len; $i+=11) {
            $chunk = substr($str, $i, 11);
            $outlen = floor( strlen($chunk)*6/8 );// 6bit/char in, 8bits/char out, round down
            $raw = gmp_strval(gmp_init(ltrim($chunk, '0'), 62), 16);// gmp doesn't like leading 0s
            $pad = str_pad($raw, $outlen * 2, '0', STR_PAD_LEFT);// double output length as as we're going via hex (4bits/char)
            $out .= pack('H*', $pad);// same as hex2bin
        }
        return $out;
    }
    return false;// unicode chars not supported
}

Demo

所有功劳归于Marcus Bointon,感谢Flash Thunder答案



也可以使用混淆器来防止用户解码变量

function obf62rep($which){// make array before translate string
    $rep    = [];
    $str1   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $str2   = 'GHIJKLMNqrstuvwx01OPQRSTUVWXYZhijklmnop23456789abcdefgyzABCDEF';
    if($which){// while obfuscate from-->to
        $fr = str_split($str1);
        $to = $str2;
    }else{// while de-obfuscate to-->from
        $fr = str_split($str2);
        $to = $str1;
    }
    foreach($fr as $k=>$v){// make array tr-->to
        $rep[$v] = $to[$k];
    }
    return $rep;
}

function obf62e($str){return strtr($str,obf62rep(1));}// translate string = obf
function obf62d($str){return strtr($str,obf62rep(0));}// translate back = deobf

Demo



然后使其更易于使用,例如

function ob62e($str){return obf62e(b62e($str));}// encode base62 + obfuscate
function ob62d($str){return b62d(obf62d($str));}// decode base62 + deobfuscate

样品用量

echo ob62e('test');

$name = ob62e('jhon');