php 由自定义数字生成的字符串

php string generating by custom number

我找到了一个代码,我可以用 PHP:

制作一个随机字符串生成器
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

但我想将我的 numeric ID 散列为散列字符串

例如我的整数 ID 是 118 所以我的散列必须是 1a

我的$chatresters是36个单词和数字,所以我的ID每36个倍数一个新字符hash

ID  HASH
36  z
38  0b
107 0z
118 1a

Hashids 是一个小型 open-source 库,可根据数字生成简短、独特的 non-sequential ID。

应该可以满足你的requirements.Official网站:http://hashids.org

一个例子:

<?php

$hashids = new Hashids\Hashids('this is my salt', 8, 'abcdefghij1234567890');

$id = $hashids->encode(1, 2, 3);
$numbers = $hashids->decode($id);

var_dump($id, $numbers);
string(5) "514cdi42"
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
<?php
function base($int, array $digits) {
    $rv = ''; $int = (int)$int;
    while($int) {
        $rv = $digits[ $int%count($digits) ] . $rv;
        $int = (int)($int/count($digits)); // use %% for php7+
    }
    return $rv;
}

function base36($int) {
    static $digits = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
    return base($int, $digits);
}

foreach( array(35, 36,38,107,118) as $i ) {
    echo base36($i), "\r\n";
}

打印

10
12
2z
3a

a) 这不是哈希;这只是使用基数的另一种表示形式!=10
b) 我想你忘记了你例子中的零 ;-)