<?php
function pass($level=2,$length=6) {
$chars[1] = "023456789abcdefghijmnopqrstuvwxyz";
$chars[2] = "23456789abcdefghijmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
$i = 0;
$str = "";
while ($i<=$length) {
$str .= $chars[$level][mt_rand(0,strlen($chars[$level]))];
$i++;
}
return $str;
}
echo pass(2, 7);
?>
当我调用该函数时,我真的无法设置任何东西。 pass(2,7)与pass(1,9)的长度相同。这都是2级和一些长度。怎么了?
答案 0 :(得分:1)
您可以使用substr []来访问。
function pass($level=1,$length=6) {
$chars = array();
$chars[0] = "023456789abcdefghijmnopqrstuvwxyz";
$chars[1] = "23456789abcdefghijmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
$i = 0;
$str = "";
while ($i<$length)
{
$index = mt_rand(0,strlen($chars[$level])-1);//It's inclusive you need -1
$str .= substr($chars[$level],$index,1);//Take the index with 1 for a single char
//You can also use:
//$str .= $chars[$level][$index];
$i++;
}
return $str;
}
echo pass(0, 7);//Start at 0 because array start at 0. So it's your Level1
echo pass(1, 7);//Start with 1, it's your Level2
?>
答案 1 :(得分:1)
其他答案似乎忽略了strings are treated as arrays of characters in php这一事实(参见字符串访问和按字符修改部分)。
通过两次修改,您的脚本对我来说很好:
您正在从0到字符串长度随机引用一个字符。这不起作用,字符串数组是0索引的,因此比长度小1。
尝试:
$str .= $chars[$level][mt_rand(0,strlen($chars[$level]) - 1)];
您正在循环执行此过程,从0到指定的长度,这意味着它将循环$length + 1
次。
尝试:
while ($i < $length) {
这对我来说非常合适。
以下是示例输出:
print pass(2, 7) //prints IR5YgGD
print pass(1, 10) //prints d2eyq547gy
答案 2 :(得分:0)
这样可以正常使用
<?php
function pass($level=2,$length=6) {
$chars[1] = array("0","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
$chars[2] = array("2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N,"P","Q","R",""S","T","U","V","W","X","Y","Z");
$i = 0;
$str = "";
while ($i<=$length) {
$str .= $chars[$level][mt_rand(0,count($chars[$level])-1)];
$i++;
}
return $str;
}
echo pass(2, 7);
?>
答案 3 :(得分:0)
这是我得到的。我定义了mt_rand()
的长度需求,然后使用花括号{}
来提取随机索引处的字符:
function pass($level=2, $length=6) {
$chars[1] = "023456789abcdefghijmnopqrstuvwxyz";
$chars[2] = "23456789abcdefghijmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
$i = 0;
$str = "";
$charLen = strlen($chars[$level]) -1;
while ($i<$length) {
$str .= $chars[$level]{mt_rand(0,$charLen)};
$i++;
}
return $str;
}
$result = pass(2, 21);