软件开发中,我们经常要使用到一些自定义函数,比如:过滤特殊字符、日期格式转换、随机字符串生成等等,在PHP中当然也不例外,这里总结了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;
}
}