如何在PHP中生成随机单词?

ABC*_*irl 8 php

如何在不重复PHP的情况下获取随机单词?救命

Ben*_*ier 14

如果您不想手动键入字母,可以执行以下操作:

<?php
function getRandomWord($len = 10) {
    $word = array_merge(range('a', 'z'), range('A', 'Z'));
    shuffle($word);
    return substr(implode($word), 0, $len);
}
Run Code Online (Sandbox Code Playgroud)

键盘示例

如果这是一个数据库ID,我建议你如下:

function createUniqueId() {
    while (1) {
       $word = getRandomWord();
       if (!idExists($word)) { // idExists returns true if the id is already used
           return $word;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)


Art*_*lov 5

试试这个功能

function randw($length=4){
        return substr(str_shuffle("qwertyuiopasdfghjklzxcvbnm"),0,$length);
    }
Run Code Online (Sandbox Code Playgroud)

  • 不鼓励仅代码答案。考虑添加至少一点点解释。 (2认同)

kar*_*m79 3

$words = preg_split('//', 'abcdefghijklmnopqrstuvwxyz0123456789', -1);
shuffle($words);
foreach($words as $word) {
    echo $word . '<br />';
}
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/function.shuffle.php

  • 如果数组可以有双精度值,请在 `shuffle()` 之前添加 `$words = array_unique($words);` (2认同)