PHP Get random paragraph

大兔子大兔子 提交于 2019-12-11 04:54:32

问题


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
<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!


回答1:


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 />';
}



回答2:


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




回答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.



来源:https://stackoverflow.com/questions/2695981/php-get-random-paragraph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!