编码类似base36,包括大写

时间:2009-09-26 13:08:54

标签: php

我使用base36来缩短网址。我有一个博客条目的id并将该id转换为base36以使其更小。 Base36只包含小写字母。如何包含大写字母?如果我使用base64_encode,它实际上会使字符串更长。

2 个答案:

答案 0 :(得分:8)

你可以找到源代码的例子来创建包含字母(大写和小写)的短网址和这两篇文章的编号,例如:

以下是第二篇文章中使用的部分代码(引用)

$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)

(如果需要,您还可以添加其他一些字符 - 具体取决于您希望在网址中获得的内容)


在评论后修改:

通过阅读第二篇文章(我从中获得了缩短代码),您将找到执行缩短代码的代码。

将该代码封装在一个函数中应该不那么难,并且可能会得到这样的结果:

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

用缩短的网址调用它:

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

会得到你:

int 123456

答案 1 :(得分:2)

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位。)