Page 1 of 1

Search through text file

Posted: Tue Jan 30, 2007 11:21 am
by djwk
I would like some code to search a text file.

Here is my text file:
Firewall*1
Scary Movie 4*2
Date Movie*3

What I want the code to do is lets say I search "Scary Movie". It will place Scary Movie 4 into the array (i'll explain why an array in a minute) named $title and the number after the asterisk into the array $id.

And if I search just "Movie" I would like to place both "Scary Movie 4" and "Date Movie" into the array $title and both "2" and "3" into the $id array.


I think I've explained this enough, if you need me to elaborate a bit more please say. Any help is appreciated.

Posted: Tue Jan 30, 2007 12:03 pm
by hawleyjr
There are some example of reading file here:

fread()

I would use that in conjunction with strpos() and explode()


I'm not sure what exactly you're trying to accomplish but it sounds like you should put this into a table ;)

Posted: Tue Jan 30, 2007 12:09 pm
by Burrito
personally, I'd use file() or file_get_contents() rather than stream the file in.

file will create an array automatically (each line is a new element), whereas file_get_contents will just create a string of the contents.

Posted: Tue Jan 30, 2007 12:56 pm
by Ollie Saunders
Yeah I'm with Burrito on this one. file() will return an array of all the lines in the file which you can iterate over looking for matches using strpos() !== false. Then explode('*', $line, 1) will allow you to separate what is before the asterisk from after it.

Posted: Tue Jan 30, 2007 1:10 pm
by djwk
Thanks for the replies.

I'm going to the pub now but I'll try it when I get back and let you know what I've managed to do :)