编码一般的4位数字数字系列

时间:2016-06-13 05:04:42

标签: php string logic sequence alphanumeric

尝试在PHP中编写一般的4位字母数字系列。

模式如下
0000
0001
....
....
9999
A000
A001
....
....
A999
B000
....
....
Z999
AA00
....
....
AA99
AB00
....
....
ZZ99
AAA0
....
....
AAA9
AAB0
....
....
ZZZZ

我试图根据Z和no中的9来制作逻辑,但是没有任何具体的结果。

我正在尝试编写一个代码,在输入系列的最后一个数字时会返回下一个系列编号。

任何提示或线索都将受到赞赏

2 个答案:

答案 0 :(得分:1)

使用PHP的内置increment operator时,这实际上非常容易,它能够处理像这样的字母数字序列。

需要手动处理两个边界异常:

  1. 进行从数字到字母数字的第一次跳转
  2. 终止系列
  3. <?php
    
    function getNext($input){
    
      // boundary cases
      switch($input){
    
        // bridge numeric to alphanumeric
        case '9999': return 'A000';
    
        // terminate sequence, instead of expanding to 5 digits 'AAAA0'
        case 'ZZZ9': return 'ZZZA';
    
        // start over
        case 'ZZZZ': return '0000';
    
      }
    
      // normal increment
      $input = substr(++$input,0,4);
    
      // pad with leading zeros
      return str_pad($input, 4, '0', STR_PAD_LEFT);
    
    }
    
    $samples = [
      '0000','9999','A000','A999','Z999','AA99',
      'ZZ99','AAA9','ZZZ9','ZZZA','ZZZY','ZZZZ'
    ];
    
    foreach ($samples as $sample)
      echo $sample . ' -> ' . getNext($sample) . PHP_EOL;
    
      <00> 0000 - &gt; 0001
      9999 - &gt; A000
      A000 - &gt; A001
      A999 - &gt; B000
      Z999 - &gt; AA00
      AA99 - &gt; AB00
      ZZ99 - &gt; AAA0
      AAA9 - &gt; AAB0
      ZZZ9 - &gt; ZZZA
      ZZZA - &gt; ZZZB
      ZZZY - &gt; ZZZZ
      ZZZZ - &gt; 0000

    See this related answer.

答案 1 :(得分:0)

您可以尝试这样的事情:

<?php

function generateNext($input) {
    $numbers = (int) preg_replace('/[^0-9]/', '', $input);
    $letters = preg_replace('/[^a-zA-Z]/', '', $input);

    if($numbers >= 99) 
    {
        $letters = ++$letters;
        $numNumbers = 4 - strlen($letters);
        if($numNumbers === 0) 
        {
            $numbers = "";
        }
        else
        {
            $numbers = str_pad("1", $numNumbers, "0", STR_PAD_LEFT);
        }

        $final = $letters.$numbers;
    }
    else if($input == "ZZZ9")
    {
        $final = "ZZZZ";
    }
    else 
    {
        $numbers = ++$numbers;
        $numNumbers = 4 - strlen($letters);
        if($numNumbers === 0) 
        {
            $numbers = "";
            $letters = ++$letters;
        }
        else
        {
            $numbers = str_pad($numbers, $numNumbers, "0", STR_PAD_LEFT);
        }

        $final = $letters.$numbers;
    }

    return $final;

}

?>