如何用 2 位数字和 4 个字母创建 6 位一次性密码?

How to create 6 digit OTP with 2 digits and 4 alphabets?

我有一个生成 6 个字符的一次性密码 (OTP) 的脚本。

代码如下:-

$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 6) as $k) 
    $rand .= $seed[$k];
$feedID = $rand;

现在,由于洗牌程序,目前所有6个都可以是数字,所有6个都可以是字母。 我想要最少和最多 2 个必填数字。

我该怎么做?

这是我的看法:

// Create a string of all alpha characters and randomly shuffle them
$alpha   = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

// Create a string of all numeric characters and randomly shuffle them
$numeric = str_shuffle('0123456789');

// Grab the 4 first alpha characters + the 2 first numeric characters
$code = substr($alpha, 0, 4) . substr($numeric, 0, 2);

// Shuffle the code to get the alpha and numeric in random positions
$code = str_shuffle($code);

如果您希望任何字符出现不止一次,请更改前两行(快速且粗略):

// Let's repeat this string 4 times before shuffle, since we need 4 characters
$alpha   = str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4));

// Let's repeat this string 2 times before shuffle, since we need 2 numeric characters
$numeric = str_shuffle(str_repeat('0123456789', 2));

并不是说这是最好的方法,但它很简单,没有循环 and/or 数组。 :)

 $seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
 $seed2= str_split('0123456789');
 $rand = [];
 for($i=mt_rand(1,2);$i<=2;$i++){
   shuffle($seed2);
   $rand[]=$seed2[0];     
 }
 while(count($rand)!=6){
  shuffle($seed);
  $rand[]=$seed[0];
 }
 shuffle($rand);
 print $feedID = implode('',$rand);

你也可以使用 random() 来生成数字 + 字母的字符串。LINK

function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

希望对您有所帮助

    function generateRandomString($length = 10,$char_len=4,$numbre_len=2) {

    $characters = '0123456789';
    $characters2='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
  $charactersLength2 = strlen($characters);
    $randomString = '';
    for ($i = 0; $i <$char_len ; $i++) {
        $randomString .= $characters2[rand(0, $charactersLength2 - 1)];
    }
  for ($i = 0; $i <$numbre_len ; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

   $shuffled = str_shuffle($randomString);
    return $shuffled;
}


 $length=7;
$char_len=6;
$numbre_len=1;
echo generateRandomString($length,$char_len,$numbre_len);

此功能可能有助于生成您想要的动态随机 otp。

多一个选择。

并不是说这是最好的方法,但它很简单,with 循环和数组。 ;)

foreach ([4 => range('A', 'Z'), 2 => range(0, 9)] as $n => $chars) {
    for ($i=0; $i < $n; $i++) {
        $otp[] = $chars[array_rand($chars)];
    }
}
shuffle($otp);
$otp = implode('', $otp);