微博数字Id与字符串Id的互转

微博数字Id与字符串Id的互转

<?php
class WeiboId
{

    public static $meta = [
        "0","1","2","3","4","5","6","7","8","9",
        "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
        "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
    ];

    /**
     * return the value of meta by given key
     * @param $key
     * @return mixed
     */
    public static function metaValue($key)
    {
        return self::$meta[$key];
    }

    /**
     * return the key of the meta by given value
     * @param $value
     * @return mixed
     */
    public static function metaKey($value)
    {
        return array_search($value,self::$meta);
    }

    /**
     * convert int piece to string piece
     * @param $value
     * @return string
     */
    public static function convertIntToStr($value)
    {
        settype($value,'integer');

        $str = '';
        while ($value != 0) {
            $key = $value % 62;
            $str .= self::metaValue($key);
            $value = floor($value / 62);
        }

        return $str;
    }

    /**
     * convert string piece to int piece
     * @param $str
     * @return int|number|string
     */
    public static function convertStrToInt($str)
    {
        $pieces = str_split($str);
        $len = strlen($str);
        $num = 0;

        for ($i = 0;$i < $len;$i++) {
            $num += pow(62, ($len - $i - 1)) * self::metaKey($pieces[$i]);
        }

        $num = str_pad($num, 7, "0", STR_PAD_LEFT);
        return $num;
    }


    /**
     * weibo  number id to string id
     * @param $id
     * @return string
     */
    public static function encodeId($id)
    {
        settype($id,'string');

        $pieces = str_split(strrev($id),7);

        $str = '';

        foreach ($pieces as $piece) {
            $str .= str_pad(self::convertIntToStr(strrev($piece)), 4, "0");
        }

        return ltrim(strrev($str), '0');
    }

    /**
     * weibo string id to number id
     * @param $str
     * @return string
     */
    public static function decodeStr($str)
    {
        $len = strlen($str);

        $parts = [];
        array_unshift($parts,substr($str, $len - 4, 4));
        array_unshift($parts,substr($str, $len - 8, 4));
        array_unshift($parts,substr($str, 0, $len - 8));

        $pieces = [];

        foreach ($parts as $key => $part) {
            $pieces[$key] = self::convertStrToInt($part);
        }

        return ltrim(implode('', $pieces), '0');
    }
}

echo WeiboId::encodeId('4235921265653191');
echo "\n";
echo WeiboId::decodeStr('Gf4twnIEv');

添加新评论