Random Sentences - PHP Snippet Needed

Discussion in 'PHP' started by Floppy233, May 18, 2010.

  1. #1
    Can somebody post a little php snippet for the following problem?

    I have a textfile like this:

    I {love|like|need} {coffee|tea}.
    He is {cool|nice|awesome} {.|..|!}
    Are you {hungry|tired|angry}?

    The little php snippet should select one line of the textfile at random and create a random sentence from it, every time i start the php-script.

    Example:

    After starting the script, it selects line 1: "I {love|like|need} {coffee|tea}."
    Then it creates a random sentence like "I like tea." or "I love coffee." (or something like this) from it.
     
    Floppy233, May 18, 2010 IP
  2. roopajyothi

    roopajyothi Active Member

    Messages:
    1,302
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    80
    #2
    You're asking me for an article rewriter right??
     
    roopajyothi, May 18, 2010 IP
  3. Floppy233

    Floppy233 Guest

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    No it's not really an article rewriter.

    The script only writes single sentences.
     
    Floppy233, May 18, 2010 IP
  4. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #4
    <?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('textfilename.txt');
    
    $file = array_map('rand_wrd', $file);
    
    //display a random sentence...
    echo $file[array_rand($file)];
    
    ?>
    PHP:
     
    danx10, May 18, 2010 IP
  5. roopajyothi

    roopajyothi Active Member

    Messages:
    1,302
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    80
    #5
    For what purpose you need? State that clearly first!
    Else it will be a crap for you!
     
    roopajyothi, May 18, 2010 IP