专业的编程技术博客社区

网站首页 > 博客文章 正文

php: 生成指定长度不重复的字符串,最低建议20个字符

baijin 2025-07-06 08:55:07 博客文章 3 ℃ 0 评论

function generateUniqueString($username, $length = 20) {
    // 使用uniqid()获取微秒级时间戳前缀
    //$prefix = uniqid();
    $time = time();
    $prefix = substr(md5($username.microtime(true)), 0, 6);
    $day = date("ymd", time());//6

    $_stuff_time = substr($time, -4);

    // 使用mt_rand()生成随机数补充剩余长度
   $random = bin2hex(random_bytes(ceil(($length-14)/2)));

    // 组合并截取到指定长度
    $result = $prefix . $day . $_stuff_time . $random;
        //echo $result."\n";
    return substr($result, 0, $length);
}

// 示例使用
echo generateUniqueString(20);

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表