Read the content of the file randomly

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
asif_phpdn
Forum Commoner
Posts: 28
Joined: Sun Aug 26, 2007 8:50 pm

Read the content of the file randomly

Post by asif_phpdn »

How can I read the content of the file(i.e,the sentences of a text file) randomly?
:?
User avatar
seppo0010
Forum Commoner
Posts: 47
Joined: Wed Oct 24, 2007 4:13 pm
Location: Buenos Aires, Argentina

Post by seppo0010 »

Weird question... does this help you?

Code: Select all

$text = file_get_contents('my_text_file.txt');
$sentences = explode('.', $text);
echo trim($sentences[array_rand($sentences)]);
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

It'd be best if you could get each sentence on a new line. If you did so, the following would be much better than searching for a sentence (periods may not delimit a sentence).

Code: Select all

<?php
$sentences = explode("\n", file_get_contents('file.txt'));
shuffle($sentences);

echo '<pre>';
print_r($sentences);
echo '</pre>';
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

file() may do well too. ;)
Post Reply