特定の文字セットに基づいて文字列の次の反復を計算する関数を次に示します。
function next_iteration($str, $charset) {
// last character in charset that requires a carry-over
$copos = strlen($charset)-1;
// starting with the least significant digit
$i = strlen($str)-1;
do {
// reset carry-over flag
$co = false;
// find position of digit in charset
$pos = strpos($charset, $str[$i]);
if ($pos === false) {
// invalid input char at position $i
return false;
}
// check whether it’s the last character in the charset
if ($pos === $copos) {
// we need a carry-over to the next higher digit
$co = true;
// check whether we’ve already reached the highest digit
if ($i === 0) {
// no next iteration possible due to fixed string length
return false;
}
// set current digit to lowest charset digit
$str[$i] = $charset[0];
} else {
// if no carry-over is required, simply use the next higher digit
// from the charset
$str[$i] = $charset[$pos+1];
}
// repeat for each digit until there is no carry-over
$i--;
} while ($co);
return $str;
}
$str = 'aaa';
$charset = 'abc';
do {
var_dump($str);
} while (($str = next_iteration($str, $charset)) !== false);