Skip to content Skip to sidebar Skip to footer

Php Get Random Paragraph

Anyone know how to get a random set of lines from a text file? I want to get a set of 3 lines with on the front of each and display them through html. example: set 1 &l

Solution 1:

Put all the possibilities in an array and then us array_rand() I guess.

Solution 2:

You can use array_chunk to create a single array comprised of sub-arrays of a specified size:

$fileArr = file('someFile.txt');

// randomize the array$lines = array_rand($fileArr, 3);

// break it into a single array comprised of arrays of three elements$chunks = array_chunk($lines, 3);

// read out values of each sub-arrayforeach($chunksas$chunk) {
    echo$chunk[0] . '<br />';
    echo$chunk[1] . '<br />';
    echo$chunk[2] . '<br />';
    echo'<br />';
}

Solution 3:

If the chunks in the text file are always split by the blank line you can ready the file into a single string then split by \n\n. Then from there grab a random element from that array.

Post a Comment for "Php Get Random Paragraph"