我正在尝试从字符串创建一个随机字符串。
$input = "123456789012345678901234567890";
$pieces = str_split($input);
$rand_keys = array_rand($pieces , 10);
$str = implode("", $rand_keys);
echo $str;
$input = "abcdefghilmnoABCDEFGHIKLMNO1234567890";
$pieces = str_split($input);
$rand_keys = array_rand($pieces , 10);
$str = implode("", $rand_keys);
echo $str;
但输出字符串很奇怪。看看:http://codepad.org/FwLU05DC
他们都工作:(我更喜欢第一个)
$input = "123456789012345678901234567890";
$pieces = str_split($input);
foreach(array_rand($pieces , 10) as $key){
$str .= $pieces[$key];
}
echo $str;
string str_shuffle ( string $str )
最后:
$pieces = str_split('12345678901234567890abcdefghiklmnopqrstuvxyzABCDEFGHIKLMNOPQTUSVXYZW');
foreach(array_rand($pieces , 15) as $key){ $str .= $pieces[$key]; }
答案 0 :(得分:3)
为什么不能使用str_shuffle?!
string str_shuffle ( string $str )
答案 1 :(得分:2)
public function generateString($what, $length) {
$chars = $what;
$rand = '';
for ($i = 0; $i < $length; $i++) {
$rand .= $chars[rand(0, strlen($chars) -1)];
}
return $rand;
}
$randstring = generateString($input, 10);
echo $randstring;
答案 2 :(得分:2)
以下是您的代码更新,以便为您提供所需内容...
<?php
$input = "123456789012345678901234567890";
$pieces = str_split($input);
foreach(array_rand($pieces , 10) as $key){
$str .= $pieces[$key];
}
echo $str;
?>