Base10 to base64 url shortening

前端 未结 8 911
小鲜肉
小鲜肉 2021-01-03 05:08

I\'m coding an url shortener function for a project in which I\'m learning php, here is the code (btw I suppose that global here is not a good thing to do :P):<

8条回答
  •  心在旅途
    2021-01-03 05:22

    By the way, check out the base_convert() function (http://php.net/manual/en/function.base-convert.php):

    echo base_convert(1000000000, 10, 36);
    

    36 is the longest base it can convert to, though. But in the comments section I found this:

    function dec2any( $num, $base, $index=false ) {
        if (! $base ) {
            $base = strlen( $index );
        } else if (! $index ) {
            $index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base );
        }
        $out = "";
        for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
            $a = floor( $num / pow( $base, $t ) );
            $out = $out . substr( $index, $a, 1 );
            $num = $num - ( $a * pow( $base, $t ) );
        }
        return $out;
    }
    
    echo dec2any(1000000000, 64, "_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    

    Maybe it will help?

提交回复
热议问题