Home>Article>Backend Development> Examples of mutual conversion between numerical ordinal and alphabetical numbers for PHP learning

Examples of mutual conversion between numerical ordinal and alphabetical numbers for PHP learning

little bottle
little bottle forward
2019-04-25 13:34:38 2211browse

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 '
', int_to_chr_1(8848); echo '
', int_to_chr_2(8848); echo '
', 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!

php
Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete