This article mainly introduces the simple random string generation method in PHP, and analyzes the related techniques and precautions for PHP to generate random strings in the form of examples. Friends in need can refer to the following
The examples in this article describe PHP simple random string generation method. I share it with you for your reference. The details are as follows:
<?php function 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 Internet for PHP functions of random strings and found that most implementations use loops. --This is a bit inefficient. In php, there are various functions that you can't think of, but no one else can think of. The str_shuffle() function can easily randomize strings. However, it is better to encapsulate one, after all, there are People have the need to use only uppercase letters and numbers.
The second parameter of the function, num, lower, and upper, can be combined at will.
The real core statement is only one line
substr(str_shuffle($src), 0, $length)
The function is to shuffle the string $src and intercept the first $length characters.
The above is the entire content of this article, I hope it will be helpful to everyone learning helps.
Related recommendations:
PHPHow to format MYSQL to return float type_php tips
PHPA large summary of mathematical operation functions (classics worth collecting)_php skills
PHPArray function array_multisort() usage example analysis_php skills
The above is the detailed content of Detailed explanation of php random string generation method. For more information, please follow other related articles on the PHP Chinese website!