PHP实现把数字ID转字母ID


Posted in PHP onAugust 12, 2013

ID是网站中经常出现的,它一般是数字,但是我们发现现在的网站很多ID都是字母了,比如YouTube的视频播放页它的URL类似/watch?v=yzNjIBEdyww。 下面是一个生成字母ID的方法。
使用示例:

   alphaID(12354);  //会将数字转换为字母。
   alphaID('PpQXn7COf',true);//会将字母ID转换为对应的数字。
   alphaID(12354,false,6);//指定生成字母ID的长度为6.

源码:
<?php
/**
 * Translates a number to a short alhanumeric version
 *
 * Translated any number up to 9007199254740992
 * to a shorter version in letters e.g.:
 * 9007199254740989 --> PpQXn7COf
 *
 * specifiying the second argument true, it will
 * translate back e.g.:
 * PpQXn7COf --> 9007199254740989
 *
 * this function is based on any2dec && dec2any by
 * fragmer[at]mail[dot]ru
 * see: http://nl3.php.net/manual/en/function.base-convert.php#52450
 *
 * If you want the alphaID to be at least 3 letter long, use the
 * $pad_up = 3 argument
 *
 * In most cases this is better than totally random ID generators
 * because this can easily avoid duplicate ID's.
 * For example if you correlate the alpha ID to an auto incrementing ID
 * in your database, you're done.
 *
 * The reverse is done because it makes it slightly more cryptic,
 * but it also makes it easier to spread lots of IDs in different
 * directories on your filesystem. Example:
 * $part1 = substr($alpha_id,0,1);
 * $part2 = substr($alpha_id,1,1);
 * $part3 = substr($alpha_id,2,strlen($alpha_id));
 * $destindir = "/".$part1."/".$part2."/".$part3;
 * // by reversing, directories are more evenly spread out. The
 * // first 26 directories already occupy 26 main levels
 *
 * more info on limitation:
 * - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/165372
 *
 * if you really need this for bigger numbers you probably have to look
 * at things like: http://theserverpages.com/php/manual/en/ref.bc.php
 * or: http://theserverpages.com/php/manual/en/ref.gmp.php
 * but I haven't really dugg into this. If you have more info on those
 * matters feel free to leave a comment.
 *
 * @author  Kevin van Zonneveld <kevin@vanzonneveld.net>
 * @author  Simon Franz
 * @author  Deadfish
 * @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD Licence
 * @version   SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $
 * @link    http://kevin.vanzonneveld.net/
 *
 * @param mixed   $in    String or long input to translate
 * @param boolean $to_num  Reverses translation when true
 * @param mixed   $pad_up  Number or boolean padds the result up to a specified length
 * @param string  $passKey Supplying a password makes it harder to calculate the original ID
 *
 * @return mixed string or long
 */
function alphaID($in, $to_num = false, $pad_up = false, $passKey = null)
{
  $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if ($passKey !== null) {
    // Although this function's purpose is to just make the
    // ID short - and not so much secure,
    // with this patch by Simon Franz (http://blog.snaky.org/)
    // you can optionally supply a password to make it harder
    // to calculate the corresponding numeric ID    for ($n = 0; $n<strlen($index); $n++) {
      $i[] = substr( $index,$n ,1);
    }
    $passhash = hash('sha256',$passKey);
    $passhash = (strlen($passhash) < strlen($index))
      ? hash('sha512',$passKey)
      : $passhash;
    for ($n=0; $n < strlen($index); $n++) {
      $p[] =  substr($passhash, $n ,1);
    }
    array_multisort($p,  SORT_DESC, $i);
    $index = implode($i);
  }
  $base  = strlen($index);
  if ($to_num) {
    // Digital number  <<--  alphabet letter code
    $in  = strrev($in);
    $out = 0;
    $len = strlen($in) - 1;
    for ($t = 0; $t <= $len; $t++) {
      $bcpow = bcpow($base, $len - $t);
      $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
    }
    if (is_numeric($pad_up)) {
      $pad_up--;
      if ($pad_up > 0) {
        $out -= pow($base, $pad_up);
      }
    }
    $out = sprintf('%F', $out);
    $out = substr($out, 0, strpos($out, '.'));
  } else {
    // Digital number  -->>  alphabet letter code
    if (is_numeric($pad_up)) {
      $pad_up--;
      if ($pad_up > 0) {
        $in += pow($base, $pad_up);
      }
    }
    $out = "";
    for ($t = floor(log($in, $base)); $t >= 0; $t--) {
      $bcp = bcpow($base, $t);
      $a   = floor($in / $bcp) % $base;
      $out = $out . substr($index, $a, 1);
      $in  = $in - ($a * $bcp);
    }
    $out = strrev($out); // reverse
  }
  return $out;
}
PHP 相关文章推荐
PHP伪静态页面函数附使用方法
Jun 20 PHP
php与XML、XSLT、Mysql的结合运用实现代码
Nov 19 PHP
PHP删除目录及目录下所有文件的方法详解
Jun 06 PHP
php缓冲 output_buffering和ob_start使用介绍
Jan 30 PHP
自定义session存储机制避免会话保持问题
Oct 08 PHP
通过php添加xml文档内容的方法
Jan 23 PHP
php使用Session和文件统计在线人数
Jul 04 PHP
php使用Header函数,PHP_AUTH_PW和PHP_AUTH_USER做用户验证
May 04 PHP
对比PHP对MySQL的缓冲查询和无缓冲查询
Jul 01 PHP
Zend Framework校验器Zend_Validate用法详解
Dec 09 PHP
PHP使用PDO调用mssql存储过程的方法示例
Oct 07 PHP
laravel 数据验证规则详解
Oct 23 PHP
PHP计算2点经纬度之间的距离代码
Aug 12 #PHP
php读取csv文件后,uft8 bom导致在页面上显示出现问题的解决方法
Aug 10 #PHP
浅析php中常量,变量的作用域和生存周期
Aug 10 #PHP
浅析linux下apache服务器的配置和管理
Aug 10 #PHP
本地机apache配置基于域名的虚拟主机详解
Aug 10 #PHP
php 删除目录下N分钟前创建的所有文件的实现代码
Aug 10 #PHP
php中如何判断一个网页请求是ajax请求还是普通请求
Aug 10 #PHP
You might like
php array_intersect()函数使用代码
2009/01/14 PHP
关于PHP中Object对象的笔记分享
2011/06/28 PHP
PHP读取txt文件的内容并赋值给数组的代码
2011/11/03 PHP
php使用curl检测网页是否被百度收录的示例分享
2014/01/31 PHP
在Yii2中使用Pjax导致Yii2内联脚本载入失败的原因分析
2016/03/06 PHP
laravel 验证错误信息到 blade模板的方法
2019/09/29 PHP
javascript 密码强度验证规则、打分、验证(给出前端代码,后端代码可根据强度规则翻译)
2010/05/18 Javascript
jQuery 操作option的实现代码
2011/03/03 Javascript
js获取鼠标点击的位置实现思路及代码
2014/05/09 Javascript
使用node.js 获取客户端信息代码分享
2014/11/26 Javascript
简单谈谈json跨域
2016/03/13 Javascript
js登录滑动验证的实现(不滑动无法登陆)
2018/01/03 Javascript
Bootstrap Table列宽拖动的方法
2018/08/15 Javascript
快速解决vue在ios端下点击响应延时的问题
2018/08/27 Javascript
详细讲解如何创建, 发布自己的 Vue UI 组件库
2019/05/29 Javascript
vue模块移动组件的实现示例
2020/05/20 Javascript
深入分析JavaScript 事件循环(Event Loop)
2020/06/19 Javascript
Vue前端判断数据对象是否为空的实例
2020/09/02 Javascript
微信小程序之高德地图多点路线规划过程示例详解
2021/01/18 Javascript
[57:59]EG vs Secret 2018国际邀请赛淘汰赛BO3 第一场 8.22
2018/08/23 DOTA
Python数据结构之Array用法实例
2014/10/09 Python
PyTorch学习笔记之回归实战
2018/05/28 Python
基于pycharm导入模块显示不存在的解决方法
2018/10/13 Python
浅谈pycharm出现卡顿的解决方法
2018/12/03 Python
python实现获取单向链表倒数第k个结点的值示例
2019/10/24 Python
python的range和linspace使用详解
2019/11/27 Python
Python通过类的组合模拟街道红绿灯
2020/09/16 Python
阿拉伯世界最大的电子商务网站:Souq沙特阿拉伯
2016/10/28 全球购物
Europcar比利时:租车
2019/08/26 全球购物
加拿大鞋网:Globo Shoes
2019/12/26 全球购物
介绍一下Java的安全机制
2012/06/28 面试题
护士自我评价
2014/02/01 职场文书
整理Python中常用的conda命令操作
2021/06/15 Python
HTML5 语义化标签(移动端必备)
2021/08/23 HTML / CSS
MySQL分区以及建索引的方法总结
2022/04/13 MySQL
MySQL数据库表约束讲解
2022/06/21 MySQL