Search through text file

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
djwk
Forum Commoner
Posts: 56
Joined: Tue Mar 07, 2006 2:14 pm

Search through text file

Post 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.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post 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 ;)
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
djwk
Forum Commoner
Posts: 56
Joined: Tue Mar 07, 2006 2:14 pm

Post 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 :)
Post Reply