Skip to content

Instantly share code, notes, and snippets.

@sepehr
Last active January 10, 2025 04:19
Show Gist options
  • Save sepehr/3371339 to your computer and use it in GitHub Desktop.
Save sepehr/3371339 to your computer and use it in GitHub Desktop.
PHP: Human-readable Random String
<?php
/**
* Generates human-readable string.
*
* @param string $length Desired length of random string.
*
* retuen string Random string.
*/
function readable_random_string($length = 6)
{
$string = '';
$vowels = array("a","e","i","o","u");
$consonants = array(
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
);
$max = $length / 2;
for ($i = 1; $i <= $max; $i++)
{
$string .= $consonants[rand(0,19)];
$string .= $vowels[rand(0,4)];
}
return $string;
}
@streetlife
Copy link

Thank you for this code. I added a caller function to randomize the length of the words and make it look like a "proper" sentence.

function readable_random_word($length = 6) {  
    $string = '';
    $vowels = array("a","e","i","o","u");  
    $consonants = array(
        'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 
        'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
    );  

    $max = $length / 2;
    for ($i = 1; $i <= $max; $i++)
    {
        $string .= $consonants[rand(0,19)];
        $string .= $vowels[rand(0,4)];
    }

    return $string;
}

function readable_random_sentence($length = 6) {
    $sentence = "";
    for ($i = 0; $i < $length; $i++) {
        $word_length = rand(3, 8);  // get random length for the word
        $word = readable_random_word($word_length); // get the word
        $sentence .= $word . " "; // add the word to the sentence
    }

    return $sentence;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment