字母数字 在 PHP 中递增字符串(到一定长度)


Alphanumeric Increment a string in PHP (To a certain length)

我需要用字母数字增量器生成一个序列(或函数来获取"下一个id")。

字符串的长度必须是可定义的,字符必须是 0-9,A-Z。

例如,长度为 3:

000
001
002
~
009
00A
00B
~
00Z
010
011
etc..

所以我想这个函数可能是这样用的:

$code = '009'
$code = getNextAlphaNumeric($code);
ehco $code; // '00A'

自己正在研究这个问题的解决方案,但很好奇是否有人以前解决这个问题,并提出了比我自己的更聪明/更强大的解决方案。

有没有人对这个问题有很好的解决方案?

像base_convert这样的东西会起作用吗?也许沿着这些路线(未经测试)

function getNextAlphaNumeric($code) {
   $base_ten = base_convert($code,36,10);
   return base_convert($base_ten+1,10,36);
}

这个想法是,你的代码实际上只是一个基数 36 的数字,所以你将这个基数 36 的数字转换为基数 10,加 1,然后将其转换回基数 36 并返回它。

编辑:刚刚意识到代码可能存在任意字符串长度,但这种方法可能仍然可行 - 如果您首先捕获所有前导零,然后将它们剥离,进行基数 36 -> 基数 10 转换,添加一个,然后添加回任何需要的前导零......

我会做这样的事情:

getNextChar($character) {
    if ($character == '9') {
        return 'A';
    }
    else if ($character == 'Z') {
        return '0';
    }
    else {
        return chr( ord($character) + 1);
    }
}
getNextCode($code) {
    // reverse, make into array
    $codeRevArr = str_split(strrev($code));
    foreach($codeRevArr as &$character) {
        $character = getNextChar($character);
        // keep going down the line if we're moving from 'Z' to '0'
        if ($character != '0') {
            break;
        }
    }
    // array to string, then reverse again
    $newCode = strrev(implode('', $codeRevArr));
    return $newCode;
}

我对这个问题的更通用的解决方案感兴趣 - 即以任意顺序处理任意字符集。我发现最简单的方法是先翻译成字母索引,然后再翻译回来。

function getNextAlphaNumeric($code, $alphabet) {
  // convert to indexes
  $n = strlen($code);
  $trans = array();
  for ($i = 0; $i < $n; $i++) {
     $trans[$i] = array_search($code[$i], $alphabet);
  }
  // add 1 to rightmost pos
  $trans[$n - 1]++;
  // carry from right to left
  $alphasize = count($alphabet);
  for ($i = $n - 1; $i >= 0; $i--) {
     if ($trans[$i] >= $alphasize) {
       $trans[$i] = 0;
       if ($i > 0) {
         $trans[$i -1]++;
       } else {
         // overflow
       }
     }
  }
  // convert back
  $out = str_repeat(' ', $n);
  for ($i = 0; $i < $n; $i++) {
     $out[$i] = $alphabet[$trans[$i]];
  }
  return $out;
}
$alphabet = array();
for ($i = ord('0'); $i <= ord('9'); $i++) {
  $alphabet[] = chr($i);
}
for ($i = ord('A'); $i <= ord('Z'); $i++) {
  $alphabet[] = chr($i);
}
echo getNextAlphaNumeric('009', $alphabet) . "'n";
echo getNextAlphaNumeric('00Z', $alphabet) . "'n";
echo getNextAlphaNumeric('0ZZ', $alphabet) . "'n";
<?php
define('ALPHA_ID_LENGTH', 3);
class AlphaNumericIdIncrementor {
 // current id
 protected $_id;
 /**
  * check if id is valid
  *
  * @param  string  $id
  * @return bool
  **/
 protected static function _isValidId($id) {
  if(strlen($id) > ALPHA_ID_LENGTH) {
   return false;
  }
  if(!is_numeric(base_convert($id, 36, 10))) {
   return false;
  }
  return true;
 }
 /**
  * format $id
  * fill with leading zeros and transform to uppercase
  *
  * @param  string  $id
  * @return string
  **/
 protected static function _formatId($id) {
  // fill with leading zeros
  if(strlen($id) < ALPHA_ID_LENGTH) {
   $zeros = '';
   for($i = 0; $i < ALPHA_ID_LENGTH - strlen($id); $i++) {
    $zeros .= '0';
   }
   $id = strtoupper($zeros . $id);
  } else {
   $id = strtoupper($id);
  }
  return $id;
 }
 /**
  * construct
  * set start id or null, if start with zero
  *
  * @param  string  $startId
  * @return void
  * @throws Exception
  **/
 public function __construct($startId = null) {
  if(!is_null($startId)) {
   if(self::_isValidId($startId)) {
    $this->_id = $startId;
   } else {
    throw new Exception('invalid id');
   }
  } else {
   $this->_generateId();
  }
 }
 /**
  * generate start id if start id is empty
  *
  * @return void
  **/
 protected function _generateId() {
  $this->_id = self::_formatId(base_convert(0, 10, 36));
 }
 /**
  * return the current id
  *
  * @return string
  **/
 public function getId() {
  return $this->_id;
 }
 /**
  * get next free id and increment $this->_id
  *
  * @return string
  **/
 public function getNextId() {
  $this->_id = self::_formatId(base_convert(base_convert($this->_id, 36, 10) + 1, 10, 36));
  return $this->_id;
 }
}
$testId = new AlphaNumericIdIncrementor();
echo($testId->getId() . '<br />'); // 000
echo($testId->getNextId() . '<br />'); // 001
$testId2 = new AlphaNumericIdIncrementor('A03');
echo($testId2->getId() . '<br />'); // A03
echo($testId2->getNextId() . '<br />'); // A04
$testId3 = new AlphaNumericIdIncrementor('ABZ');
echo($testId3->getId() . '<br />'); // ABZ
echo($testId3->getNextId() . '<br />'); // AC0
?>
function formatPackageNumber($input)
 { 
  //$input = $_GET['number'];
  $alpha_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");
  $number_array = array("0", "1" , "2", "3", "4", "5", "6", "7", "8", "9");
  $output = "";
  for($i=0; $i<=5; $i++){
     if($i>=4) {
      $divisor = pow(26,$i-3)*pow(10,3);
    } else {
      $divisor = pow(10,$i);
    }
    $pos = floor($input/$divisor);
    if($i>=3) {
      $digit = $pos%26;
      $output .= $alpha_array[$digit];
    } else {
      $digit = $pos%10 ;
      $output .= $number_array[$digit];
    }
  } 
return  strrev($output);

}