function Random::word

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::word()
  2. 8.9.x core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::word()
  3. 10 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::word()

Generate a string that looks like a word (letters only, alternating consonants and vowels).

Parameters

int $length: The desired word length.

Return value

string

File

core/lib/Drupal/Component/Utility/Random.php, line 193

Class

Random
Defines a utility class for creating random data.

Namespace

Drupal\Component\Utility

Code

public function word($length) {
    $vowels = [
        "a",
        "e",
        "i",
        "o",
        "u",
    ];
    $cons = [
        "b",
        "c",
        "d",
        "g",
        "h",
        "j",
        "k",
        "l",
        "m",
        "n",
        "p",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "tr",
        "cr",
        "br",
        "fr",
        "th",
        "dr",
        "ch",
        "ph",
        "wr",
        "st",
        "sp",
        "sw",
        "pr",
        "sl",
        "cl",
        "sh",
    ];
    $num_vowels = count($vowels);
    $num_cons = count($cons);
    $word = '';
    while (strlen($word) < $length) {
        $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
    }
    return substr($word, 0, $length);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.