Page 1 of 1

Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 3:46 pm
by shanehunter
So, here's my dilemma,

I'm calling a random line of text from another file, using the following code:

Code: Select all

	function RandomLine($seed) {
	$textfile = "links.txt";		
	$sites = array();
		if(file_exists($textfile)){		
		     $sites = file($textfile);		
		     srand ($seed);		
		     $string = $sites[array_rand($sites)];		
		} else {
		     $string = "Error";
		}
	return $string;
	}
	
	$s0 = RandomLine(rand((float) microtime(), 10000000));

echo $s0;
This code works well. But now, my next problem, is once that line is called, I would like to remove it from the file that it was called from, so that it will not duplicate.

Please help! =)

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 4:24 pm
by requinix
array_rand gives you a key in the array. Once you have that key (and the value associated with it) unset the item in the array and put the lines back into the original file.

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 4:35 pm
by shanehunter
haha...

i'm sorry, but i'm far too low on the IQ scale to understand what you just said. lol.

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 5:37 pm
by requinix
Right here

Code: Select all

$sites = file($textfile);
srand ($seed);
$string = $sites[array_rand($sites)];
it reads each line in the $textfile into the $sites array. Then it uses array_rand to locate the array key of a random line and puts that random line into $string.

Since $sites has everything in $textfile, and you want to remove that one line from the file, you can remove it from $sites instead and then save what's left back into $textfile.
If you hold onto the random key that array_rand gave you (by putting it into a variable rather than using it immediately) you can remove the line from $sites by using unset. To "save" the modification you then call file_put_contents.

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 5:54 pm
by shanehunter
so from that, I've got:

Code: Select all


$array[$s0] = $text; 
unset($sites[$text]); 

is that right? and what is an easy code to write the array back to a text file

minus the unset $text

?

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 7:29 pm
by requinix
Getting close.

Code: Select all

$lines = file($textfile); // as before
$key = array_rand($lines); // save this to a variable first
$string = $lines[$key]; // mostly as before

unset($lines[$key]); // remove it from the list
file_put_contents($textfile, $lines); // save the list back to the file

Re: Strip a specific line of text from another fle

Posted: Sun Jun 27, 2010 7:59 pm
by shanehunter
<edit> nevermind. i still don't get it...

lol. i apologize for the idiocy here, but I do believe I may be in over my head. :roll: :banghead: