在PHP中将integer更改为短字符串


change integer to a short string in PHP

我想用与十六进制相同的方式将PHP中的长整数缩短为字符串。我认为谷歌也使用这一点在YouTube中的排序网址。

我有一串数字和字母要使用:0123456789BCDEFGHIJKLMNOPQRSTUVWXYZ

其中:

8 = 8
a = 10
f = 15
Z = 61
10 = 62
11 = 63
1a = 72
and zo on...

其目的是在关联url子id中的参数中以最排序的方式设置一个整数以进行跟踪。

我正在寻找一个好名字来描述我的问题,我发现有一个以60为基数的六进制数字系统。

在这里,你可以找到一个缩短url并避免类似字符(如0/o和i/1/l/l等)之间的混淆的函数。

<?php
/**
 * A pure PHP implementation of NewBase60. A base 60 numbering system designed for 
 * use with URL shortening. Limited/overlapping character set to avoid confusion
 * between similar characters, eg o/0, i/l, etc.
 *
 * Q: Why not use PHP base_convert()?
 * A: Because it only goes up to base 36, and doesn't support the  NewBase60
 *
 * @see http://tantek.pbworks.com/w/page/19402946/NewBase60
 * @see http://en.wikipedia.org/wiki/sexagesimal
 *
 * @author david@dsingleton.co.uk
 */
class NewBase60
{
protected static $characterSet =  '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz';
/**
 * Convert a sexagesimal number to a decimal number
 * @param string sexagesimal number to convert
 * @return integer Decimal representation of sexagesimal number
 */
public static function toDecimal($sexNum)
{
    // Return falsy and 0 values as is
    if (!$sexNum) {
        return $sexNum === '0' ? 0 : $sexNum;
    }
    $decNum = 0;
    foreach(str_split($sexNum) as $chr) {
        $ord = ord($chr);
        if ($ord>=48 && $ord<=57)       { $ord -= 48; } // 0 - 9
        elseif ($ord>=65 && $ord<=72)   { $ord -= 55; } // A - H
        elseif ($ord==73 || $ord==108)  { $ord =  1; }  // Error correct typo: capital I, lowercase l to 1
        elseif ($ord>=74 && $ord<=78)   { $ord -= 56; } // J - N
        elseif ($ord==79)               { $ord =  0; }  // Error correct typo: capital O to 0
        elseif ($ord>=80 && $ord<=90)   { $ord -= 57; } // P - Z
        elseif ($ord==95)               { $ord =  34; } // underscore
        elseif ($ord>=97 && $ord<=107)  { $ord -= 62; } // a - k
        elseif ($ord>=109 && $ord<=122) { $ord -= 63; } // m - z
        else { $ord = 0; }                              // treat all other noise as 0
        $decNum = 60 *$decNum + $ord;
    }
    return $decNum;
}
/**
 * Convert a decimal number to a sexagesimal number
 * @param integer Decimal number to convert
 * @return string sexagesimal representation of decimal
 */
public static function fromDecimal($decNum)
{
    $decNum = (int) $decNum;
    if (!$decNum) {
        return $decNum === 0 ? '0' : $sexNum;
    }
    $aSexCharset = self::$characterSet;
    $result = '';
    while ($decNum > 0) {
      $decRemainder = $decNum % 60;
      $decNum = ($decNum - $decRemainder) / 60;
      $result = $aSexCharset[$decRemainder] . $result;
    }
    return $result;
}
}

版权所有:https://github.com/dsingleton/new-base-60/blob/master/newbase60.class.php