MENU

将数字转为短网址代码

October 14, 2018 • 已被 267 位童鞋围观过 • 代码分享

/**
 * 将数字转为短网址代码
 *
 * @param int $number 数字
 * @return string 短网址代码
 */
function generate_code($number) {
  $out  = "";
  $codes = "abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  while ($number > 60) {
    $key  = bcmod($number,'61');
    $number = bcsub(bcdiv($number,'61'),'1');
    $out  = $codes{$key}.$out;
  }
  return $codes{$number}.$out;
}
/**
 * 将短网址代码转为数字
 *
 * @param string $code 短网址代码
 * @return int 数字
 */
function get_num($code){
  $codes = "abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $num = 0;
  $i = strlen($code);
 for($j=0;$j<strlen($code);$j++){
    $i--;
    $char = $code{$j};
    $pos = strpos($codes,$char);
    $num = bcadd(bcmul(bcpow("61", $i),($pos + 1)),$num);
  }
  $num=bcsub($num,"1");
  return  $num;
}
/*****函数结束****/

$id="1973337397412392446";
echo $id."<br/>";
$did=generate_code($id);
echo generate_code($id)."<br/>";
echo get_num($did);
Last Modified: September 28, 2023