如何从字母中获取反向数字代码?

I have function which encoding numbers to string like:

  • 0 -> a
  • 1 -> b
  • 2 -> c
  • ...
  • 45 -> R

Function:

public static function encode($number) {
    $out = "";
    $codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ";

    while ($number > 53) {
        $key = $number % 54;
        $number = floor($number / 54) - 1;
        $out = $codes{$key}.$out;
    }

    return $codes{$number}.$out;
}

How to make reverse function which will convert letters back to number?

Its easy to use the strpos function

public static function decode($letter) {

    $letter = $letter[0];

    $codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ";

    $pos = strpos($codes,$letter);

    return $pos;

}

You can treat a string like an array and use the position, so this would be easier to encode:

$codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ";
return $codes[$number];

You may want some error checking like:

return isset($codes[$number]) ? $codes[$number] : false;

Then to decode, find the letter at that position:

$codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ";
return strpos($codes, $letter);

strpos() will return false for you if not found.