生成所有 6 个字符的字母数字组合(大写和小写)

Generating all 6 character alphanumeric combinations (upper and lower case)

我正在尝试找出一种方法来生成每个可能的 6 字符字母数字字符串的列表,其中大写和小写字母被视为唯一字母。使用以下函数,我们可以使用小写字母和数字生成字符串:

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

但是,这不考虑大写字母。在 PHP?

这种算法中是否可以同时使用大写和小写字母

只需要添加一个小块来处理大写字符:

<?php

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 = 65; //one past 9, go to A
    }

    if ($nChar == 91) {
        $nChar = 97; //one past Z, 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(6);