如何在PHP中使用小写字母和数字增加字母数字字符串?

时间:2017-03-17 20:12:42

标签: php

我想知道如何只用小写字母(a-z)和数字(0-9)来增加一个字母数字字符串。我正在尝试检查字符串的所有可能组合,这是64个字符长,所以字符串看起来像 g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gh (对于那些你认为它的人来说,字符串是哈希函数的种子)。字符串需要从结尾增加到开头。有没有办法增加它?

1 个答案:

答案 0 :(得分:1)

我们定义了一个字母“0123456789abcdefghijklmnopqstuvxzyz”。假设增量从末尾到开头起作用,每个增量将“加”一个字母表的ASCII值:

例如:

  

“a”将变为“b”

     

“0”将变为“1”

     

“9”将成为“a”

     

“z”将变为“0”

     

“abc” - > “ABD”

     

“01z” - > “020”

     

...

     

以下算法将起作用:

<?php


class Increment {
    private $alphabet;

    public function __construct($alphabet)
    {
        $this->alphabet = $alphabet;
    }

    public function getNext($text)
    {
        $length = strlen($text);
        $increment = true;
        for ($i=$length; $i--; $i > 0) {
            $currentCharacter = $text[$i];
            if ($increment) {
                $increment = $this->hasReachEndOfAlphabet($currentCharacter);
                $text[$i] = $this->getIncrementedCharacter($currentCharacter);

            }
        }

        return $text;
    }

    private function getIncrementedCharacter($currentCharacter)
    {
        $position = strpos($this->alphabet, $currentCharacter);
        if (!$this->hasReachEndOfAlphabet($currentCharacter)) {
            return $this->alphabet[++$position];
        }

        return $this->alphabet[0];
    }

    private function hasReachEndOfAlphabet($currentCharacter)
    {
        $position = strpos($this->alphabet, $currentCharacter);
        if ($position < strlen($this->alphabet) -1) {
            return false;
        }

        return true;
    }
} //end of class

$text = "g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gh";
$alphabet = "0123456789";
for ($i=97;$i<=122;$i++) {
    $alphabet .= chr($i);
}
$increment = new Increment($alphabet);
$next = $increment->getNext($text);

print_r($next.PHP_EOL); // outputs g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gi