生成随机的5个字符的字符串 [英] Generate random 5 characters string

查看:107
本文介绍了生成随机的5个字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建精确的5个随机字符串,并尽可能减少重复.最好的方法是什么?谢谢.

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.

推荐答案

$rand = substr(md5(microtime()),rand(0,26),5);

将是我最好的猜测-除非您也正在寻找特殊字符:

Would be my best guess--Unless you're looking for special characters, too:

$seed = str_split('abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

示例

而且,对于一个基于时钟的时钟(由于它是递增的,因此减少了冲突):

And, for one based on the clock (fewer collisions since it's incremental):

function incrementalHash($len = 5){
  $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  $base = strlen($charset);
  $result = '';

  $now = explode(' ', microtime())[1];
  while ($now >= $base){
    $i = $now % $base;
    $result = $charset[$i] . $result;
    $now /= $base;
  }
  return substr($result, -5);
}

注意:增量意味着更容易猜测;如果您将其用作盐或验证令牌,请不要使用.盐(现在)为"WCWyb"表示从现在起5秒钟为"WCWyg")

这篇关于生成随机的5个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆