php - 在 PHP 中将整数转换为字母数字序列

标签 php integer converter alphanumeric 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;
    }
?>

虽然它有效,但我的一些数字(数据库 ID)输出了奇怪的简码:

1 -> 2 2 -> 3 ... 10 -> 丙 11 -> d 12 -> 电子 ...

有什么简单的方法可以修改此代码,使我生成的短代码长于一个字符(每个短代码至少两个或三个字符),即使对于 1、2、3 等整数也是如此?

还有谁能告诉我,上面的算法如何输出整数的短代码?

提前致谢

最佳答案

您想将该数字转换为另一种表示法 - 一种同时包含字母和数字的表示法,例如 base 36,它实际上是字母数字 -> a-z + 0-9。

所以你需要做的是:

$string = base_convert ( $number , 10, 36 );

文档:

string base_convert ( string $number , int $frombase , int $tobase );

关于php - 在 PHP 中将整数转换为字母数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21780503/

相关文章:

WPF 触发 VS Converter

maven - 将Maven Pom转换为Gradle构建

php - Laravel 5.2 如何通过 Laravel Eloquent 模型连接三个表

php - MySQL group_concat 并与另一个 group_concat 嵌套

php - 使用 jquery 验证表单并使用 jquery 中的 php 提交(if form.valid()

error-handling - 是否可以根据有限范围变量的超出范围值覆盖 Common Lisp 中的类型错误行为?

计算给定字符串的 float 的长度

apache - 防止在没有 .htaccess 的情况下从 Apache 访问文件

c++ - "Dividing"一个整数分成几 block (对某些收入阈值征收不同的税 - C++)

java - 将整数参数复制到数组元素中