-3

我需要一个函数来为数据库的每个输入增加“字母/数字”。就像 INT 数据的 AI。

我需要这个来制作一个短链接代码,比如site.com/1gHrT.

任何想法如何做到这一点?

4

4 回答 4

1

URL 缩短器通常在 base62 中使用大整数。

整数通常在 base10 中(这是十进制系统的另一个词,即 ie [0-9])。还有其他常见的系统,例如 base2 ( [0-1])、base8 ([ 0-8]) 和 base16 ( [0-f])。

当您超过 base10 时,习惯上使用英文小写字母 ( [a-z])。所以,base16 是[0-9a-f]( 0123456789abcdef)。如果您将基数推到超出数字和小写字母可以处理的范围,那么您通常使用大写字母 ( [A-Z])。因此,base62 使用[0-9a-zA-Z].

在 PHP 中,该base_convert()函数可以处理从 base2 到 base36(或[0-1]to [0-9a-z])的任何内容。

如果你想超越 base36 那么你需要可以处理任何内容的gmp扩展base62。如果您没有gmp安装扩展,那么您应该能够在互联网上的某处找到一个功能。此外,虽然该base64_encode()功能听起来可能相关,但在这种情况下并非如此。它对data 进行编码,这与更改 base (或radix)不同。

但是,您需要记住,base62 在网络上可能有点脆弱。这是因为小写和大写字母都有意义。换句话说,如果某个聪明人或女孩更喜欢小写 URI,并将其转换为小写,那么 URI 将指向错误的位置。从这个意义上说,base36 更安全,但 URI 不会那么短(尽管不会那么短)。

现在,如果您想增加帖子中的数字,只需将其转换为 base10,增加它,然后再将其转换回来。

如果我们假设它确实是在 base62 中,那么我们可以使用以下gmp函数:

function base62_increment($number, $incrBy = 1) {
    if ( ! defined('GMP_VERSION'))
        throw new \Exception(__FUNCTION__.' needs the GMP extension');
    $number = gmp_init($number, 62);
    $number = gmp_add($number, $incrBy);
    return gmp_strval($number, 62);
}
$base62 = '1gHrT';
$incremented = base62_increment($base62);
var_dump($base62, $incremented);

如果你想使用 base36,或者如果你没有gmp安装扩展,那么我们可以使用base_convert()

function base36_increment($number, $incrBy = 1) {
    $number = base_convert($number, 36, 10);
    $number += $incrBy;
    return base_convert($number, 10, 36);
}
$base36 = 'esq2f';
$incremented = base36_increment($base36);
var_dump($base36, $incremented);

就是这样。

于 2013-02-26T12:40:17.460 回答
0

也许你在追求类似的东西?

function randLetter()
{
return chr(97 + mt_rand(0, 25));
}

来源: http: //maymay.net/blog/2004/12/19/generating-random-letters-in-php/

于 2013-02-26T12:24:26.913 回答
0

您可以使用给定的字符将数字转换为字符串,就像您使用以下算法将一个系统中的数字转换为另一个系统一样

$n = 123; //your number

$chars = "abcdefghijklmnopqrstuvwxyz";
$chars = "0123456789" . strtoupper($chars) . $chars;
$b = strlen($chars);
$nums = array();
while ($n > 0) {
    $nums[] = $n % $b;
    $n = (int)($n / $b);
}

$nums = array_reverse($nums);
$out = "";
foreach ($nums as $num) {
    $out .= $chars[$num];
}

在内部,您可以使用数字计数器,并使用此算法生成输出..

于 2013-02-26T12:24:35.913 回答
0

未经测试,可能会进行优化以避免转换,但这会将数字转换为数字,但这会将顺序整数转换为字符串。

$startval = 12435;
$maxval = 12654;

for ($i = $startval; $i < maxval; $i++) {
    $strINT = strval($i); // convert int to string
    // intialize final string to empty
    $strOutput = '';
    /* Loop through each letter */
    foreach (explode($strINT) as $letter) {
        // add 65 to each letter and turn it into a letter
        // letter A is character 65
        $strOutput .= chr(intval($letter) + 65);
    }
}
于 2013-02-26T12:50:19.970 回答