有一个包含字符的字符串[a-zA-Z0-9]
.这应该是26*2 + 10 = 62个可能在一个字符和62 ^ 2两个.增加这样一个字符串的值的首选方法是什么,以便'aA'变成'aB'等?PHP中是否有任何内置的东西,这可以帮助吗?
我知道你可以增加一个字符串,但这只是小写字母.基本上,结果应该以61个增量从"a"变为"aa".
这对我有用:
<?php
$str = 'a';
echo ++$str; // b
$str = 'z';
echo ++$str; // aa
$str = 'aA';
echo ++$str; // aB
Run Code Online (Sandbox Code Playgroud)
试试这个功能:
<?php
function increment(&$string){
$last_char=substr($string,-1);
$rest=substr($string, 0, -1);
switch ($last_char) {
case '':
$next= 'a';
break;
case 'z':
$next= 'A';
break;
case 'Z':
$next= '0';
break;
case '9':
increment($rest);
$next= 'a';
break;
default:
$next= ++$last_char;
}
$string=$rest.$next;
}
//sample
$string='a';
for($i=1;$i<=128;$i++){
echo $string."<br>";
increment($string);
}
?>
Run Code Online (Sandbox Code Playgroud)
@simshaun 不适合我。我检查了文档,发现base_convert可以为您工作(在 base 35 上),并且有一条评论“ francesco[at]paladinux.net ”,其中包含可以在 base65 上工作的函数。
所以解决方案可以是:
转换为 b10 -> 增量 +1 -> 转换基数 65
编辑1
谈到转换,我认为转换为 Base64 编码,因此我使用 Base64 编码/解码数字编写了这 2 个函数。不幸的是,使用的字符集有点大:[a-zA-Z0-9/+=],但使用内部函数更有效。
零 0 是“AA==”
function nencode($in){
$res ="";
while(1){
$b = $in & 0xff;
$res = chr($b) . $res;
if($in > 0xff){
$in = $in >> 8;
} else {
break;
}
}
return base64_encode($res);
}
function ndecode($in){
$rv=0;
$res =base64_decode($in);
for($t = 0 ; $t < strlen($res) ; $t++){
if($t>0){
$rv = $rv << 8;
}
$c = ord($res{$t});
$rv |= $c;
}
return $rv;
}
Run Code Online (Sandbox Code Playgroud)