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

时间:2012-08-17 06:46:27

标签: php

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

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

例如,长度为3:

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

所以我想这个函数可能会像这样使用:

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

我正在努力解决这个问题,但很奇怪,如果有人之前已经解决了这个问题,并提出了比我自己更聪明/更强大的解决方案。

有没有人能解决这个问题呢?

5 个答案:

答案 0 :(得分:8)

像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转换,添加一个,并添加任何所需的前导零......

答案 1 :(得分:1)

我会做这样的事情:

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;
}

答案 2 :(得分:1)

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

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";

答案 3 :(得分:1)

<?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
?>

答案 4 :(得分:0)

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);

}