Encoding as base36, including uppercase

I use base36 to shorten urls. I have a blog entry id and convert that id to base36 to make it smaller. Base36 only includes lowercase letters. How can I include capital letters? If I use base64_encode, this actually makes the string longer.

+6
source share
2 answers

you can find examples of source code for creating short links containing letters (both lower and upper case) and a number for these two articles, for example:

Here is part of the code used in this second article (citation):

$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$n = 300;
$converted = "";

while ($n > 0) {
  $converted = substr($codeset, ($n % $base), 1) . $converted;
  $n = floor($n/$base);
}

echo $converted; // 4Q

- , , , $n :

function shorten($n) {
    $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($codeset);
    $converted = "";
    while ($n > 0) {
      $converted = substr($codeset, ($n % $base), 1) . $converted;
      $n = floor($n/$base);
    }
    return $converted;
}

:

$id = 123456;
$url = shorten($id);
var_dump($url);

:

string 'w7e' (length=3)

( , - , URL-)


:

( ), , .

- :

function unshorten($converted) {
    $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($codeset);
    $c = 0;
    for ($i = strlen($converted); $i; $i--) {
      $c += strpos($codeset, substr($converted, (-1 * ( $i - strlen($converted) )),1)) 
            * pow($base,$i-1);
    }
    return $c;
}

url:

$back_to_id = unshorten('w7e');
var_dump($back_to_id);

:

int 123456
+8
function dec2any( $num, $base=62, $index=false ) {

    // Parameters:
    //   $num - your decimal integer
    //   $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62))
    //   $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu")

    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;
}

PHP base_convert() (base_convert() 32).

+2

All Articles