I've tried writing the function myself, though it doesn't work as expected and now I see the logic flaw.
$string = 'aaaaaa';
function hp_update_uid($string)
{
$position = strpos($string, '9');
if($position === 0)
{
return FALSE;
}
elseif($position === FALSE)
{
$position = -1;
}
else
{
$position = -(7-$position);
}
#var_dump($position);
#exit;
$character_ord = ord(substr($string, $po开发者_如何学Gosition, 1));
if($character_ord == 122)
{
$character_ord = 65;
}
elseif($character_ord == 90)
{
$character_ord = 48;
}
else
{
++$character_ord;
}
$string = substr_replace($string, chr($character_ord), $position, 1);
return $string;
}
for($i = 0; $i < 1000; $i++)
{
$string = hp_update_uid($string);
echo $string . '<br />';
}
This will produce the following output: https://gist.github.com/937b148a126924b9429d
How do I really generate 6 characters long unique ID using only a-z A-Z 0-9 and using logical increase?
How do I really generate 6 characters long unique ID using only a-z A-Z 0-9 and using logical increase?
If they need to increase by steps of 1, start at 0, then increase by 1 and convert the resulting number in base62 (26 from [A-Z] + 26 from [a-z] + 10 from [0-9]).
Stop when the length no longer fits (62^6 - 1
if I am not mistaking).
You can use this function:
function Base($number, $input, $output, $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
if (strlen($charset) >= 2)
{
$input = max(2, min(intval($input), strlen($charset)));
$output = max(2, min(intval($output), strlen($charset)));
$number = ltrim(preg_replace('~[^' . preg_quote(substr($charset, 0, max($input, $output)), '~') . ']+~', '', $number), $charset[0]);
if (strlen($number) > 0)
{
if ($input != 10)
{
$result = 0;
foreach (str_split(strrev($number)) as $key => $value)
{
$result += pow($input, $key) * intval(strpos($charset, $value));
}
$number = $result;
}
if ($output != 10)
{
$result = $charset[$number % $output];
while (($number = intval($number / $output)) > 0)
{
$result = $charset[$number % $output] . $result;
}
$number = $result;
}
return $number;
}
return $charset[0];
}
return false;
}
Example usage (@ IDEOne.com):
$i = -1;
$string = '';
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
while (strlen($string) <= 6)
{
echo $string = str_pad(Base(++$i, 10, 62, $charset), 6, 'a', STR_PAD_LEFT);
}
精彩评论