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
<br>
on the front of each and display them through html.
example:
set 1
<br>Hi
<br>what's your name
&开发者_StackOverflowlt;br>goodbye
set 2
<br>stack
<br>overflow
<br>hi there
set 3,4,5....
Choose one random set and display it. The sets of lines would be stored in a text file.
Thanks a lot!
Put all the possibilities in an array and then us array_rand() I guess.
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-array
foreach($chunks as $chunk) {
echo $chunk[0] . '<br />';
echo $chunk[1] . '<br />';
echo $chunk[2] . '<br />';
echo '<br />';
}
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.
精彩评论