PHP code for generating decent-looking coupon code

2019-01-23 15:25发布

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).

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.

Something like perhaps,

AHS3DJ6BW 
B83JS1HSK

(I typed that, so it's not really that random)

标签: php random
10条回答
不美不萌又怎样
2楼-- · 2019-01-23 15:49

http://webarto.com/35/php-random-string-generator

Here you go.

function randr($j = 8){
$string = "";
    for($i=0;$i < $j;$i++){
        srand((double)microtime()*1234567);
        $x = mt_rand(0,2);
        switch($x){
            case 0:$string.= chr(mt_rand(97,122));break;
            case 1:$string.= chr(mt_rand(65,90));break;
            case 2:$string.= chr(mt_rand(48,57));break;
        }
    }
return strtoupper($string); //to uppercase
}
查看更多
smile是对你的礼貌
3楼-- · 2019-01-23 15:51
function generateCouponCode($length = 8) {
  $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $ret = '';
  for($i = 0; $i < $length; ++$i) {
    $random = str_shuffle($chars);
    $ret .= $random[0];
  }
  return $ret;
}
查看更多
成全新的幸福
4楼-- · 2019-01-23 15:54

Why don't keep it simple?

<?php
    echo strtoupper(uniqid());
?>

Always returns 13 character long uppercased random code.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-23 15:56
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 10; $i++) {
    $res .= $chars[mt_rand(0, 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.

查看更多
家丑人穷心不美
6楼-- · 2019-01-23 15:57

Try this:

substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10)
查看更多
Animai°情兽
7楼-- · 2019-01-23 15:58

You can use the coupon code generator PHP class file to generate N number of coupons and its customizable, with various options of adding own mask with own prefix and suffix. Simple PHP coupon code generator

Example: coupon::generate(8); // J5BST6NQ

查看更多
登录 后发表回答