Random Sentence script

Discussion in 'PHP' started by Chris Gwynne, Mar 10, 2013.

  1. #1
    I have the following simple script.

    <?php
     
    function rand_wrd($input){
    if (!is_array($input)){
    return preg_replace_callback('~\{(.+?)\}~', 'rand_wrd', $input);
    } else {
    $input = explode("|", $input[1]);
    return $input[array_rand($input)];
    }
    }
     
    //the text file containing the sentences....
    $file = file('test.txt');
     
    $file = array_map('rand_wrd', $file);
     
    //display a random sentence...
    echo $file[array_rand($file)];
     
    ?>
    PHP:
    With my text file being as such
    I {love|like|need} {coffee|tea}.
    He is {cool|nice|awesome} {.|..|!}
    Are you {hungry|tired|angry}?
    Code (markup):
    Which is then outputted into <span class="random">(word) {insert randomly generated sentence}</span>

    What I'm trying to achieve is to also randomly add {insert randomly generated sentence} after or before (word). Any ideas?
     
    Chris Gwynne, Mar 10, 2013 IP
  2. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #2
    You mean you want it the text file to have:

    {D3Tek|Chris Gwynne} is {cool|nice|awesome}

    And then it would output something like:

    Chris Gwynne is nice.

    I think that's what you mean. I'll let you confirm before I code it for you though! :)
     
    D3Tek, Mar 11, 2013 IP
  3. Nathan Malone

    Nathan Malone Well-Known Member

    Messages:
    369
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Nathan Malone, Mar 11, 2013 IP