• PHP 数字序数&字母序数 相互转化


    数从1开始  即 A=1  而非 A=0

     1 <?php
     2 
     3 /**
     4  * 数字序列转字母序列
     5  * @param $int
     6  * @return bool|mixed|string
     7  */
     8 function int_to_chr($int)
     9 {
    10   if (!is_int($int) || $int <= 0) return false;
    11 
    12   $array = array('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');
    13 
    14   if ($int > 26) {
    15     $_count_times = floor($int / 26);
    16     $_left_int = $int - $_count_times * 26;
    17     if ($_left_int > 0) $chr = $array[$_left_int - 1];
    18     else  $chr = $array[25];//26倍数时,尾数为Z
    19 
    20     if ($_count_times > 26) {
    21       if ($_left_int > 0) {
    22         $chr = int_to_chr((int)$_count_times) . $chr;
    23       } else {
    24         $chr = int_to_chr((int)($_count_times - 1)) . $chr;
    25       }
    26     } else if ($_count_times <= 26 && $_count_times > 0) {
    27       if ($_left_int > 0) {
    28         $chr = $array[$_count_times - 1] . $chr;
    29       } else {
    30         if ($_count_times > 1) $chr = $array[$_count_times - 2] . $chr;
    31       }
    32     }
    33   } else {
    34     $chr = $array[$int - 1];
    35   }
    36 
    37   return $chr;
    38 }
    39 
    40 
    41 /**
    42  * 字母序列转数字序列
    43  * @param $char
    44  * @return int|bool
    45  */
    46 function chr_to_int($char)
    47 {
    48   //检测字符串是否全字母
    49   $regex = '/^[a-zA-Z]+$/i';
    50 
    51   if (!preg_match($regex, $char)) return false;
    52 
    53   $int = 0;
    54   $char = strtoupper($char);
    55   $array = array('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');
    56   $len = strlen($char);
    57   for ($i = 0; $i < $len; $i++) {
    58     $index = array_search($char[$i], $array);
    59     $int += ($index + 1) * pow(26, $len - $i - 1);
    60   }
    61   return $int;
    62 }
    63 
    64 echo '8848:', int_to_chr(8848), '<br>';
    65 echo 'MBH:', chr_to_int('MBH'), '<br>';
  • 相关阅读:
    Azure SQL Database (1) 用户手册
    Windows Azure Web Site (17) Azure Web Site 固定公网IP地址
    MongoDB数据文件内部结构
    压缩 MongoDB 的数据文件
    服务器如何选择网络带宽(转)
    刀片服务器和磁盘阵列卡(RAID)技术---永和维护(转)
    Solr打分出错
    Solr添加SolrDocument报错
    解决Windows Git Bash中文乱码问题
    HAProxy的独门武器:ebtree
  • 原文地址:https://www.cnblogs.com/PHPcoder404/p/9635706.html
Copyright © 2020-2023  润新知