本篇文章小编将和大家分享一下如何用php实现数字序数和字母序数的相互转化的代码示例,具有一定的参考价值,感兴趣的朋友可以看看,希望对你有所启发。
序数从1开始 即 a=1
/** * 数字序列转字母序列 * @param $int * @param int $start * @return string|bool */ function int_to_chr_1($int, $start = 64) { if (!is_int($int) || $int <= 0) return false; $str = ''; if (floor($int / 26) > 0) { $str .= int_to_chr_1((int)floor($int / 26)); } return $str . chr($int % 26 + $start); } /** * 数字序列转字母序列 * @param $int * @return string|bool */ function int_to_chr_2($int) { if (!is_int($int) || $int <= 0) return false; $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'); $str = ''; if ($int > 26) { $str .= int_to_chr_2((int)floor($int / 26)); $str .= $array[$int % 26 - 1]; return $str; } else { return $array[$int - 1]; } } /** * 字母序列转数字序列 * @param $char * @return int|bool */ function chr_to_int($char) { //检测字符串是否全字母 $regex = '/^[a-za-z]+$/i'; if (!preg_match($regex, $char)) return false; $int = 0; $char = strtoupper($char); $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'); $len = strlen($char); for ($i = 0; $i < $len; $i++) { $index = array_search($char[$i], $array); $int += ($index + 1) * pow(26, $len - $i - 1); } return $int; } echo '<br>', int_to_chr_1(8848); echo '<br>', int_to_chr_2(8848); echo '<br>', chr_to_int('mbh');
相关教程:php视频教程
以上就是php学习之数字序数和字母序数的相互转化示例的详细内容。