PHP:生成字符串的所有可能的字母数字组合

时间:2015-09-11 12:31:30

标签: php string

上下文:我有一个函数,我将字符串的长度设置为参数,假设为8.该函数生成一个从AAAAAAAA到ZZZZZZZZ的字符串。它实际上生成了1个组合,将其存储在txt文件中,重新加载网页,然后尝试下一个组合:AAAAAAAA - >刷新 - > AAAAAAAB - >刷新 - > ... - > ZZZZZZZY --->刷新 - >泣鬼神

代码:它看起来非常像这样(我删除了所有不必要的部分以便你的方便)

function combinations($size) {
    $string = str_repeat('a',$size);
    $endLoopTest = str_repeat('z',$size);
    $endLoopTest++;
    while ($string != $endLoopTest) {
        echo $string++,PHP_EOL;
    }
}

问题:它适用于从A到Z的字符,但我也想考虑数字字符(0到9)。 “$ string ++”技巧在PHP中非常方便,因为我可以增加字符串。现在我想添加数字字符,我需要完全重写这个函数的逻辑。

精确度:我仍然希望一次生成1个字符串 - >刷新页面 - > “增加”前一个字符串 - >生成新字符串 - >刷新 - >等

1 个答案:

答案 0 :(得分:3)

这可能不如你想要的那么优雅......但是它显示了一种方法来做你想做的事 - 也许它会教你一些新东西。

function increasePosition(&$cString, $nPosition) {
    //get the char of the current position
    $cChar = substr($cString, $nPosition - 1, 1);

    //convert to the ascii value (and add one)
    $nChar = ord($cChar) + 1;

    if ($nChar == 58) {
        $nChar = 97; //one past 9, go to a
    }

    if ($nChar == 123) {
        $nChar = 48; //one past z, go to 0
        //we hit z, so increase the next space to the left
        increasePosition($cString, $nPosition - 1);
    }

    //replace the expected position with the new character
    $cString[$nPosition - 1] = chr($nChar);
}

function myCombinations($nSize) {
    //init to 0 repeating.
    $cString = str_repeat('0', $nSize);
    //move the last character 'back' one, so that 0 repeating will be the first item.
    $cString[$nSize - 1] = '/';
    //when to stop.
    $cEnd = str_repeat('z', $nSize);

    while ($cString != $cEnd) {
        increasePosition($cString, $nSize);
        print($cString . " ");
    }
}

myCombinations(2);
相关问题