簡體   English   中英

PHP7中的隨機字符串

[英]Random string in PHP7

我試圖用PHP7的嶄新random_bytes()函數創建一個8和12個隨機字符串。

PHP官方文檔也只是一個例子,如何創建通過使用BIN2HEX十六進制字符串()。 有較大的隨意性我想生成的字母數字[A-ZA-Z0-9]串,但不能找到一種方法如何實現這一目標。

在此先感謝您的幫助
寧斯基

使用隨機字節的ASCII碼作為字符數組(或字符串)的索引。 像這樣:

// The characters we want in the output
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$count = strlen($chars);

// Generate 12 random bytes
$bytes = random_bytes(12);

// Construct the output string
$result = '';
// Split the string of random bytes into individual characters
foreach (str_split($bytes) as $byte) {
    // ord($byte) converts the character into an integer between 0 and 255
    // ord($byte) % $count wrap it around $chars
    $result .= $chars[ord($byte) % $count];
}

// That's all, folks!
echo($result."\n");

您可以使用另外兩種方法。 從[a-zA-Z0-9]制作陣列,然后1.從該陣列中取出6或8個隨機元素2.洗改此陣列,並從開始或陣列的任何部分中取出6或8個元素

<?php

$small_letters = range('a', 'z');
$big_letters = range('A', 'Z');
$digits = range (0, 9);

$res = array_merge($small_letters, $big_letters, $digits);
$c = count($res);
// first variant

$random_string_lenght = 8;
$random_string = '';
for ($i = 0; $i < $random_string_lenght; $i++)
{
    $random_string .= $res[random_int(0, $c - 1)];
}

echo 'first variant result ', $random_string, "\n";

// second variand
shuffle($res);
$random_string = implode(array_slice($res, 0, $random_string_lenght));
echo 'second variant result ', $random_string, "\n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM