Generate random 5 characters string(生成随机 5 个字符的字符串)
本文介绍了生成随机 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 个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:生成随机 5 个字符的字符串


猜你喜欢
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01