Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform integer to alphanumeric sequence in PHP [closed]

I'm working on a url shortener. I based mine on this one https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener and more or less took the function to create the short codes, because i couldn't come up with an algorithm myself:

<?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;
    }
?>

Although it works, some of my numbers (database id) output strange shortcodes:

1 -> 2 2 -> 3 ... 10 -> c 11 -> d 12 -> e ...

Is there any easy way i can modify this code, so that my generated short codes are longer than just one character (at least two or three characters for every shortcode), even for integers like 1, 2, 3 etc.?

Also is there anybody who can tell me, how this algorithm above works to output short codes for integers?

Thanks in advance

like image 856
Daniel Avatar asked Jan 28 '26 11:01

Daniel


1 Answers

What you would like to do is convert that number to a different notation - one that includes both letters and numbers like base 36 which is actually alphanumeric -> a-z + 0-9.

So what you would need to do is:

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

Documentation:

string base_convert ( string $number , int $frombase , int $tobase );
like image 125
Itay Grudev Avatar answered Jan 31 '26 01:01

Itay Grudev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!