【问题标题】:How to increment alphanumeric string with just lower case letters and numbers in PHP?如何在 PHP 中仅使用小写字母和数字来增加字母数字字符串?
【发布时间】:2017-03-17 20:12:41
【问题描述】:

我想知道如何增加仅包含小写字母 (a-z) 和数字 (0-9) 的字母数字字符串。我正在尝试检查字符串的所有可能组合,长度为 64 个字符,因此字符串看起来像 g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gh (对于那些认为它的人,字符串是散列函数的种子)。字符串需要从末尾递增到开头。有没有办法增加它?

【问题讨论】:

  • 你的意思是加一,将最后一个“h”转换为“i”?
  • 这是那些更难理解的问题之一
  • 请提供一些相关的代码示例。我们很乐意为您提供帮助,但我们现在无法看到您的屏幕或您的屏幕......
  • Possible duplicate,或者至少足够接近 - 将一个大的 36 基数转换为十进制,递增,然后再转换回来。

标签: php


【解决方案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

【讨论】:

  • 非常感谢!我什至从未想过添加自己的字母表并使用它!
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2014-10-08
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 2018-02-03
相关资源
最近更新 更多