PHP - Select 5 random characters in a string?
如何从给定的字符串中随机选择5个字符?他们可以重复。
假设我的字符串是:
1 | static $chars ="123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"; |
我只想从这个变量中提取5个随机字符。感谢任何能帮助我的人!
1 2 3 4 5 6 | function gen_code() { $charset ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; return substr(str_shuffle($charset), 0, 5); } |
号
它起作用了,请试试看,
1 2 3 4 5 | <?php $length = 5; $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); echo $randomString; ?> |
。
只需创建5个随机索引并从字符串中获取字符:
1 2 3 4 5 6 7 8 |
。
如果你只想得到一个5个字符长的随机字符串,那么有更好的方法。从操作系统中获取随机数据,然后对其进行编码,这将是理想的方法:
1 2 3 4 5 6 7 | function random_string($length) { $raw = (int) ($length * 3 / 4 + 1); $bytes = mcrypt_create_iv($raw, MCRYPT_DEV_URANDOM); $rand = str_replace('+', '.', base64_encode($bytes)); return substr($rand, 0, $length); } echo random_string(5); |
1 2 3 4 5 6 7 8 9 10 | //define a function function generateRandomString($length = 5){ $chars ="123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"; return substr(str_shuffle($chars),0,$length); } //usage echo generateRandomString(5); //random string legth: 5 echo generateRandomString(6); //random string legth: 6 echo generateRandomString(7); //random string legth: 7 |
1 2 3 4 5 6 7 8 9 |
。
edit*有一个off-by-one错误,"count($var)"应为"count($var)-1"
只需将您的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // to generate random string function rand_str($length = 5, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') { // Length of character list $chars_length = (strlen($chars) - 1); // Start our string $string = $chars{rand(0, $chars_length)}; // Generate random string for ($i = 1; $i < $length; $i = strlen($string)) { // Grab a random character from our list $r = $chars{rand(0, $chars_length)}; // Make sure the same two characters don't appear next to each other if ($r != $string{$i - 1}) $string .= $r; } // Return the string return $string; } // function ends here |
试试这个
1 2 3 | static $chars ="123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"; $chars=str_shuffle($chars); $finalString=substr($chars, 0,5); |