PHP 常用工具函数大全

软件开发中,我们经常要使用到一些自定义函数,比如:过滤特殊字符、日期格式转换、随机字符串生成等等,在PHP中当然也不例外,这里总结了PHP日常开发中用到的一些自定义函数,便于我们查阅。

W3CAPI
1
2020-04-24 07:39:45
文档目录
我的书签
 

PHP 常用工具函数大全 | 生成随机字符串

随机字符串生成的应用也很普遍,我们经常可能需要给用户生成邀请码,激活码等等,在应用系统中起到一个标识作用,代码如下:
/**
 * 生成随机字符串,可以自己扩展,若想保持唯一性,只需在开头加上用户id
 * $type可以为:upper(只生成大写字母),lower(只生成小写字母),number(只生成数字)
 * $len为长度,定义字符串长度
 */
function str_random_custom($type, $len = 0) {
    $new = '';
    $string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';  //数据池
    if ($type == 'upper') {
        for ($i = 0; $i < $len; $i++) {
            $new .= $string[mt_rand(36, 61)];
        }
        return $new;
    }
    if ($type == 'lower') {
        for ($i = 0; $i < $len; $i++) {
            $new .= $string[mt_rand(10, 35)];
        }
        return $new;
    }
    if ($type == 'number') {
        for ($i = 0; $i < $len; $i++) {
            $new .= $string[mt_rand(0, 9)];
        }
        return $new;
    }
}
友情提示