Php simple random string generation method example, php string example
This example describes how to generate a simple random string in php. We will share this with you for your reference. The details are as follows:
<?phpfunction rand_str($length,$p='all'){ $nums = '0123456789'; $lowers = 'abcdefghijklmnopqrstuvwxyz'; $uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if ($p == 'all') { $src = $nums.$lowers.$uppers; } else { $src = ''; if (strpos($p, 'num') !== false) $src .= $nums; if (strpos($p, 'lower') !== false) $src .= $lowers; if (strpos($p, 'upper') !== false) $src .= $uppers; } return $src? substr(str_shuffle($src), 0, $length) : $src;}?>
I searched the php functions of random strings on the Internet and found that most implementations use loops. This is a little inefficient. in php, there are all kinds of functions that you can't think. the str_shuffle () function can easily implement random strings. however, we recommend you encapsulate it. After all, some people only need to use uppercase letters and only numbers.
The second parameter num, lower, and upper of the function can be combined at will.
The true core statement is only one line
substr(str_shuffle($src), 0, $length)
The function is to unsequence the string $ src and intercept the first $ length characters.
PS: here we will provide you with an online tool with similar functions for your reference:
Online random number/string generation tool:
Http://tools.jb51.net/aideddesign/suijishu
High-strength Password generator:
Http://tools.jb51.net/password/CreateStrongPassword