PHP generates random string program code_PHP tutorial
WBOYOriginal
2016-07-13 16:57:05941browse
Because the tool requires us to write a function that can generate random strings. I was thinking that there should be many such random string generating functions on the Internet. I searched a lot on Baidu. Now I will summarize these good PHP functions for you. .
Use a for loop to traverse the characters we defined
/**
*@blog
*/
function createRandomStr($length){
$str = array_merge(range(0,9),range('a','z'),range('A','Z'));
shuffle($str);
$str = implode('',array_slice($str,0,$length));
return $str;
}
echo createRandomStr(10);
?>
echo $s . “ ”;
?>
Can generate pure numeric strings, character strings, etc. of specified length.
(Uppercase, lowercase, uppercase and lowercase, and a combination of uppercase and lowercase and numbers can also be expanded according to preference).
$length=5 below, if you change it to 10, it will be 10 digits.
Change $str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' to $str = '0123456789' which is a pure numeric string.
The code is as follows
Copy code
function getRandStr($length) { <🎜>
$str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; <🎜>
$randString = ''; <🎜>
$len = strlen($str)-1; <🎜>
for($i = 0;$i < $length;$i ++){ <🎜>
$num = mt_rand(0, $len); <🎜>
$randString .= $str[$num]; <🎜>
} <🎜>
return $randString ; <🎜>
}<🎜>
<🎜>//How to use it is as follows<🎜>
$test=getRandStr($length=5);<🎜>
echo $test;<🎜>
?>
or use while
The code is as follows
Copy code
/**<🎜>
*/<🎜>
function createRandomStr($length){<🎜>
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62 characters<🎜>
$strlen = 62;<🎜>
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
Return substr($str,0,$length);
}
echo createRandomStr(10);
?>
Use the idea of array and character conversion:
http://www.bkjia.com/PHPjc/631543.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631543.htmlTechArticleBecause the tool requires us to write a function that can generate random strings. I think there should be many such functions on the Internet. Generate random string functions, Baidu has a lot of them, and I will give them below...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn