gpt4 book ai didi

php - Base10 到 base64 网址缩短

转载 作者:可可西里 更新时间:2023-11-01 13:35:06 25 4
gpt4 key购买 nike

我正在为我正在学习 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 这样的 url 缩短服务如果我使用它会返回一个 6 数字的 id,而且我不认为这个算法比他们的更好。

那么,两个问题:

  • 你发现上面的代码有什么错误吗?
  • 如何管理 64 个多个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com