Home > 类库下载 > PHP类库 > PHP simply generates random strings

PHP simply generates random strings

高洛峰
Release: 2016-10-20 15:27:13
Original
1574 people have browsed it

PHP simple custom method to generate random strings

/**
 * 生成随机字符串
 * @param string $lenth 长度
 * @return string 字符串
 */
function get_randomstr($lenth = 6) {
    return get_random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}
 
/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ,默认为 0123456789
 * @return   string     字符串
 */
function get_random($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
Copy after login

Usage:

echo get_randomstr(6);
echo get_randomstr(7);
Copy after login

Output:

vS8wZK
hQ17fEI
Copy after login

The above two results will be randomly generated, and the structure will be different every time it is run.


Analysis:

Pass in the number of generated strings through parameters to the method get_randomstr(); the get_randomstr() method then generates a random number through the get_random method and returns it to get_randomstr(). In fact, this process is through two I personally think it is more cumbersome to complete it with a custom method, although the idea is clear. In fact, the advantage of this method is that when we hard-code the get_random method in the public method, if we later find that some functions cannot be satisfied by get_random, we can extend it through the get_randomstr method.


So under normal circumstances, I recommend that you use the following method to generate random strings:

Several methods of generating PHP random numbers


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template