Dan*_*iel 2 php integer alphanumeric converter url-shortener
我正在努力缩短网址.我基于这一个https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener并且或多或少地使用该函数来创建短代码,因为我自己无法提出算法:
<?php
convertIntToShortCode($_GET["id"]); // Test codes
function convertIntToShortCode($id) {
$chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
$id = intval($id);
if ($id < 1) {
echo "ERROR1";
}
$length = strlen($chars);
// make sure length of available characters is at
// least a reasonable minimum - there should be at
// least 10 characters
if ($length < 10) {
echo "ERROR2";
}
$code = "";
while ($id > $length - 1) {
// determine the value of the next higher character
// in the short code should be and prepend
$code = $chars[fmod($id, $length)] . $code;
// reset $id to remaining value to be converted
$id = floor($id / $length);
}
// remaining value of $id is less than the length of
// self::$chars
$code = $chars[$id] . $code;
echo $code;
}
?>
Run Code Online (Sandbox Code Playgroud)
虽然它有效,但我的一些数字(数据库ID)输出了奇怪的短代码:
1 - > 2 2 - > 3 ... 10 - > c 11 - > d 12 - > e ...
有没有简单的方法可以修改这段代码,这样我生成的短代码只比一个字符长(每个短代码至少有两三个字符),即使对于1,2,3等整数也是如此?
还有谁能告诉我,上面这个算法如何输出整数的短代码?
提前致谢
您想要做的是将该数字转换为另一种表示法 - 一种包括字母和数字,如基数36,实际上是字母数字 - > az + 0-9.
所以你需要做的是:
$string = base_convert ( $number , 10, 36 );
Run Code Online (Sandbox Code Playgroud)
文档:
string base_convert ( string $number , int $frombase , int $tobase );
Run Code Online (Sandbox Code Playgroud)