Random sentence

This example shows how to create random (un-)meaningful sentences :-)

Here are some example output sentences:
These dogs are yellow.
These cars are deadly huge!!
This is a deadly cool sentence!
This is a fluffy sentence!
These monkeys are deadly boring!
These examples are very stupid *lol*
This is another monkey dog!?

BTW: This also works nicely with german sentences :-)

// A list of sentences:
// %something ==> is a variable 
$r_sentences = '
This is a %adjective %noun %sentence_ending
This is another %noun %noun %sentence_ending
I %love_or_hate %nouns , because it is %adjective %sentence_ending
My %family says you are not %adjective %sentence_ending
These %nouns are %adjective %sentence_ending
// This is another list of variables:
// (This list can also contain variables (like %something))
// Formatting:
// (first-line) = Variablename
// (second-line) = Variables (seperated by semicolon)
$r_variables = '
%adjective_list;very %adjective_list;deadly %adjective_list
%noun_list;%adjective %noun_list
sentence;beer;cow;monkey;donkey;example;ice cream;dog
%adjective %family_members;%family_members
// strip spaces:
$r_sentences = trim($r_sentences);
$r_variables = trim($r_variables);
// fix new lines and split sentences up:
$r_sentences = str_replace("\r\n", "\n", $r_sentences);
$r_sentences = str_replace("\r", "\n", $r_sentences);
$r_sentences = explode("\n", $r_sentences);
$r_variables = str_replace("\r\n", "\n", $r_variables);
$r_variables = str_replace("\r", "\n", $r_variables);
$r_variables = explode("\n\n", $r_variables);
// this array contains all variables:
$r_vars = array();
// go trough all variables:
for($x=0; $x < count($r_variables); $x++){
    $var = explode("\n", trim($r_variables[$x]));
    // lowecase all:
    $key = strtolower(trim($var[0]));
    // split words:
    $words = explode(";", trim($var[1]));
    // add variables to the $r_vars Array
    $r_vars[$key] = $words;
// returns a word from the variables array:
function get_word($key){
    global $r_vars;
    if (isset($r_vars[$key])){
        $words = $r_vars[$key];
        // calc max.
        $w_max = count($words)-1;
        $w_rand = rand(0, $w_max);
        // return the word, and check if the word contains
        // another variable:
        return replace_words(trim($words[$w_rand]));
    else {
        // the word was not found :-(
        return "(Error: Word '$key' was not found!)";
// this function replaces a variable like %something with
// the 	proper variable-value:
function replace_words($sentence){
    // if there are no variables in the sentence,
    // return it without doing anything
    if (str_replace('%', '', $sentence) == $sentence)
        return $sentence;
    // split the words up:
    $words = explode(" ", $sentence);
    $new_sentence = array();
    // go trough all words:
    for($w=0; $w < count($words); $w++){
        $word = trim($words[$w]);
        if ($word != ''){
            // is this word a variable?
            if (preg_match('/^%(.*)$/', $word, $m)){
                // --> yes
                $varkey = trim($m[1]);
                // get the proper word from the variable list:
                $new_sentence[] = get_word($varkey);
            else {
                // --> no it is a default word
                $new_sentence[] = $word;
    // join the array to a new sentence:
    return implode(" ", $new_sentence);    
// calc. max.
$max_s = count($r_sentences)-1;
$rand_s = rand(0, $max_s);
// get a random sentence:
$sentence = $r_sentences[$rand_s];
// format the resulting sentence, so that I looks nice:
// (delete whitespace infront of punctuation marks)
$sentence = str_replace(' ,', ',', ucfirst(replace_words($sentence)));
$sentence = str_replace(' .', '.', $sentence);
$sentence = str_replace(' !', '!', $sentence);
$sentence = str_replace(' ?', '?', $sentence);
$sentence = trim($sentence);
// finally print the new sentence! :-D
print $sentence;
Snippet Details

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!

Older comments:

GrosBedo November 12, 2010 at 16:57
Thank you for this piece of code, exactly what I needed ! I am using it to generate random but valid game logs for debugging purposes.

There is a small glitch in the code that makes it unusable in some cases (like mine !), just change this :

$r_variables = str_replace("rn", "n", $r_variables);
$r_variables = str_replace("r", "n", $r_variables);
$r_variables = explode("nn", $r_variables);

Into this :

$r_variables = str_replace("rn", "n", $r_variables);
$r_variables = str_replace("r", "n", $r_variables);
$r_variables = preg_replace("/ns*n/", "nn", $r_variables);
$r_variables = explode("nn", $r_variables);

Just add the preg_replace, this will ensure that the variables newlines are cleanly formatted.