随机数/字母值
所以我想知道在 PHP 中生成“类似十六进制”值的一些好的/首选方法是什么?最好将其限制为 5 个字符长,如下所示: 1e1f7
目前这就是我正在做的事情:
echo dechex(mt_rand(10000, 99999));
但这给了我 4-5 个字符长的值,我想保留它一致为 4 或 5。
有哪些方法可以在 PHP 中更好地生成类似的内容?有内置功能吗?
注意:当我说“类似十六进制”时,我实际上只是指字母和数字的随机组合。可用字母不必受到限制。
So I was wonder what are some good/preferred methods for generating a 'hex-like' value in PHP? Preferably, I would want to restrict it to 5 characters long like such: 1e1f7
Currently this is what I am doing:
echo dechex(mt_rand(10000, 99999));
however this gives me values anywhere from 4-5 characters long, and I want to keep it at a consistent 4 or 5.
What are some ways to better generate something like this in PHP? Is there even a built in function?
Note: When I say 'hex-like' I really just mean a random combination of letters and numbers. There does not have to be a restriction on available letters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一些简单的东西,例如:(
未经测试)
或者将您的
mt_rand
范围修复为:mt_rand(65535, 1048575)
(十六进制为 10000-fffff),或者如果您喜欢锡纸帽子:mt_rand(hexdec("10000"), hexdec("ffffff"))
的优点while 循环方法适用于任意长的字符串。如果您想要 32 个随机字符,则远远超出了整数限制,并且单个
mt_rand
将无法工作。如果你真的只是想要随机的东西,我建议:(
未经测试)
Something simple like:
(untested)
Or fix your
mt_rand
range to:mt_rand(65535, 1048575)
(10000-fffff in hex) or if you like tinfoil hats:mt_rand(hexdec("10000"), hexdec("ffffff"))
The advantage of the while-loop approach is that it works for arbitrarily long strings. If you'd want 32 random characters you're well over the integer limit and a single
mt_rand
will not work.If you really just want random stuff, I'd propose:
(untested)
由于采用 base64,这会使用更多的字母表,但请记住,它将包括大写和小写字母以及数字。
This uses more of the alphabet due to the base64, but remember that it will include upper and lower case letters along with numbers.
为什么所有工作 sha1 都经过测试并且均匀分布:
我已经使用它为分片表生成了数以百万计的 uniq uid,没有冲突并且无论您使用的长度如何,都非常均匀分布...
您甚至可以使用 sha1 的二进制形式基于 64 的哈希:
要限制字符,您可以使用正则表达式:
这里我们限制字符串中的 0,1,l(字母)和 o(字母),交换一点熵以防止混淆(和服务)门票)在所有年龄段的入场期间......
Why all the work sha1 is tested and evenly distributed:
I have used this to generate millions and millions of uniq uids for sharding tables, no collisions and remarkably evenly distributed regardless of the length you use...
you can even use binary form of sha1 hash for base 64:
to limit characters, you can use a regex:
Here we limited 0,1,l (letter), and o (letter) from the string, trading a little entropy to prevent confusion (and service tickets) during entry for all ages...