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散列为散列字符串

例如,我的Integer id是118,所以我的哈希必须是1a

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

ID  HASH
36  z
38  0b
107 0z
118 1a
<?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) 我想你在例子中忘记了零;-)

Hashids是一个小型开源库,它从数字中生成短的、唯一的、非序列的id。

它应该能够满足您的要求。官方网站: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)
}