我正在为正在学习php的项目编写url缩短功能,这是代码(顺便说一句,我想这里global
并不是一件好事:P):
$alphabet = array(1 => "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",
"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",
"0","1","2","3","4","5","6","7","8","9","_","-");
function shorten($id){
global $alphabet;
$shortenedId = "";
while($id>0){
$remainder = $id % 64;
$id = $id / 64;
$shortenedId = $alphabet[$remainder].$shortenedId;
}
return $shortenedId;
}
该代码取自this Wikipedia article并适用于php。我的问题是,当我将64的倍数传递给函数时,我得到了一个错误的结果(出于我的目的),例如128返回不正确的b,应该是aaa,但是对于3位数字来说太长了数字。
我也开始认为这段代码有问题,如果我将1'000'000'000'000作为
$id
传递,我得到nItOq ...我觉得这是错误的,因为诸如bit.ly这样的网址缩短服务返回了如果我使用6个数字ID,我认为该算法并不比他们的算法更好。因此,有两个问题:
最佳答案
仅需进行一些小调整,主要的两个调整是使字母零索引而不是一索引,并在除法之前从id中减去余数
function shorten($id)
{
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
$shortenedId = '';
while($id>0) {
$remainder = $id % 64;
$id = ($id-$remainder) / 64;
$shortenedId = $alphabet{$remainder} . $shortenedId;
};
return $shortenedId;
}
这是进一步的修改版本...嗯,我就像
function shorten($id, $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
{
$base = strlen($alphabet);
$short = '';
while($id) {
$id = ($id-($r=$id%$base))/$base;
$short = $alphabet{$r} . $short;
};
return $short;
}
编辑:对串联进行排序,使其与OP相同
关于php - Base10到base64网址缩短,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3199771/