phpuniqueidentifierbase-conversion

Generating 5 digit alphanumeric code with predifined characters in sequence


I would like to generate a membership number consisting of alphanumeric characters, removing i o and l to save confusion when typing. to be done in php (also using Laravel 5.7 if that matters - but i feel this is a php question)

If simply using 0-9 the membership number would start at 00001 for the 1st one and the 11th person would have 00011. I would like to use alphanumeric characters from 0-9 + a-z (removing said letters)

0-9 (total 10 characters), abcdefghjkmnpqrstuvwxyz (total 23 characters) - this giving a total of 33 characters in each count cycle (0-10+a-Z). instead of just 10 (0-10)

So the first membership number would still be 00001 where as the 12th would now be 0000a, 14th 0000c and 34th would be 0001a.

To summarize i need a way of defining the characters for counting in a way that can be generated based on the id of a user.

I hope I have explained this well enough.


Solution

  • Assuming that these are the only characters you want to use:

    0123456789abcdefghjkmnpqrstuvwxyz
    

    You can use base_convert() and strtr() to translate specific characters of the result to the characters you want.

    function mybase33($number) {
        return str_pad(strtr(base_convert($number, 10, 33), [
            'i' => 'j',
            'j' => 'k',
            'k' => 'm',
            'l' => 'n',
            'm' => 'p',
            'n' => 'q',
            'o' => 'r',
            'p' => 's',
            'q' => 't',
            'r' => 'u',
            's' => 'v',
            't' => 'w',
            'u' => 'x',
            'v' => 'y',
            'w' => 'z',
        ]), 5, '0', STR_PAD_LEFT);
    }
    
    echo "9 is ".mybase33(9)."\n";
    echo "10 is ".mybase33(10)."\n";
    echo "12 is ".mybase33(12)."\n";
    echo "14 is ".mybase33(14)."\n";
    echo "32 is ".mybase33(32)."\n";
    echo "33 is ".mybase33(33)."\n";
    echo "34 is ".mybase33(34)."\n";
    

    Output:

    9 is 00009
    10 is 0000a
    12 is 0000c
    14 is 0000e
    32 is 0000z
    33 is 00010
    34 is 00011
    

    https://3v4l.org/8YtaR

    Explanation

    The output of base_convert() uses these characters:

    0123456789abcdefghijklmnopqrstuvw
    

    The strtr() translates specific characters of that output to:

    0123456789abcdefghjkmnpqrstuvwxyz