Base10到base64网址缩短 [英] Base10 to base64 url shortening
问题描述
我正在为要学习php的项目编写一个url缩短功能,下面是代码(顺便说一句,我想global
这不是一件好事:P):
I'm coding an url shortener function for a project in which I'm learning php, here is the code (btw I suppose that global
here is not a good thing to do :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;
}
该代码摘自这篇Wikipedia文章,并适用于php.我的问题是,当我将64的倍数传递给函数时,我得到了一个错误的结果(出于我的目的),例如128返回不正确的b,应该是aaa,但是对于3位数字来说太长了数字.
The code is taken from this Wikipedia article and adapted to php. My problem is that when I pass a multiple of 64 to the function I get a wrong (for my purpose) result, for instance 128 returns b which is not correct, it should have been aaa, but that's too long for a 3-digit number.
我也开始认为这段代码有问题,如果我以$id
的形式传递1'000'000'000'000,我会得到nItOq ...我觉得这是错误的,因为类似url缩短的服务如果我使用bit.ly,则会返回6个数字的ID,我认为这种算法并不比他们的算法更好.
Also I'm starting to think that there's something wrong in this code, if I pass 1'000'000'000'000 as $id
I get nItOq... I feel it's wrong because a url shortening service like bit.ly returns a 6 number id if I use it, and I don't think that this algorithm is better than theirs.
因此,有两个问题:
- 您在上面的代码中发现任何错误了吗?
- 如何管理64多个ID?我是否必须忽略它们并传递给下一个?
推荐答案
仅需进行一些细微调整,主要的两个是使字母表的索引为零而不是单索引,并从id中减去余数.划分之前
Just a couple of little tweaks needed, the main two were to make the the alphabet zero indexed rather than one-indexed, and to subtract the remainder from the id before dividing
function shorten($id)
{
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
$shortenedId = '';
while($id>0) {
$remainder = $id % 64;
$id = ($id-$remainder) / 64;
$shortenedId = $alphabet{$remainder} . $shortenedId;
};
return $shortenedId;
}
这是进一步的修改版本,...我很喜欢
and here's a further modified version which... well I just like
function shorten($id, $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
{
$base = strlen($alphabet);
$short = '';
while($id) {
$id = ($id-($r=$id%$base))/$base;
$short = $alphabet{$r} . $short;
};
return $short;
}
编辑:将串联排序为与OP相同
sorted concatenation to be the same as the OPs
这篇关于Base10到base64网址缩短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!