PHP代码,用于生成外观精美的优惠券代码(字母和数字的混合) [英] PHP code for generating decent-looking coupon codes (mix of letters and numbers)
问题描述
对于一个电子商务网站,我想生成一个看起来比随机生成的值更好的随机优惠券代码.它应该是可读的优惠券代码,全部为大写字母,没有特殊字符,只有字母(A-Z)和数字(0-9).
For an ecommerce site I want to generate a random coupon code that looks better than a randomly generated value. It should be a readable coupon code, all in uppercase with no special characters, only letters (A-Z) and numbers (0-9).
由于人们可能正在阅读此内容/将其打印到其他地方,因此我们也需要使它成为易于传达的值,也许是8到10个字符长.
Since people might be reading this out / printing it elsewhere, we need to make this a simple-to-communicate value as well, perhaps 8-10 characters long.
类似的东西,
AHS3DJ6BW
B83JS1HSK
(我输入的内容不是那么随机)
(I typed that, so it's not really that random)
推荐答案
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 10; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
您可以通过预分配$res
字符串并缓存strlen($chars)-1
的结果来优化此设置.这留给读者练习,因为您可能不会每秒生成数千张优惠券.
You can optimize this by preallocating the $res
string and caching the result of strlen($chars)-1
. This is left as an exercise to the reader, since probably you won't be generating thousands of coupons per second.
这篇关于PHP代码,用于生成外观精美的优惠券代码(字母和数字的混合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!