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>';
原文地址:https://www.cnblogs.com/PHPcoder404/p/9635706.html