The editor of this article will share with you a code example of how to use PHP to realize the mutual conversion of numerical ordinal numbers and alphabetical ordinal numbers. It has certain reference value. Friends who are interested can take a look. I hope it will be helpful to you. inspired by.
OrderThe number starts from 1, that is, 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');
Related tutorials:PHP Video tutorial
The above is the detailed content of Examples of mutual conversion between numerical ordinal and alphabetical numbers for PHP learning. For more information, please follow other related articles on the PHP Chinese website!