Jump to content


Filtering and sorting a text file

  • Please log in to reply
1 reply to this topic

#1 mycrew143

  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 05 May 2006 - 10:07 PM

I am hoping some will be able to point me in the right direction to accomplish a strange script that I am trying to write.
What I am trying to accomplish is to build a simple web page to upload a text file. This text file is then displayed in its original format.
The page is the easy part.

The following is what I am having a difficult time even to start the process.... I would like to use php because I have used it in the past even though it has been a while.
Lets say the orginal file that was uploaded and now displays on the page is like the following...

>add animal goat nani
>add animal cow milking
>add animal fish water

>add space for aquarium fish for pleasure.
>add space for coral goat for riding.
>add space for barn cow for living

>put cow in the barn for living
>put goat in the coral for riding
>put fish in the aquarium for pleasure

Just some strange sentences that are clearly related by a couple of words.
I am basically trying to filter and sort. The process would start by the user supplying the first word to filter on.

So lets say the supplied work is "corral".
This would match the following 2 lines....

>add space for corral goat for riding.
>put goat in the corral for riding

The second part of this is to also display an additional line based on a position of a particular line in the output above. Lets say this position is the 5th position of a line that also match a static string like 'add space'. In this case the word goat. Now display the previous 2 lines plus the line that matches goat. The results is like

>add space for coral goat for riding.
>put goat in the coral for riding
>add animal goat nani

I am hoping someone could point in the right direction. What would be the best program? awk/sed with PHP?

#2 Kris

  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 07 May 2006 - 10:53 PM

Heres a list of functions that you could use to write your script...

file() - To dump the contents of your text file into an array, loop through it with a foreach loop.
strpos() - To see if your search term is found in the current line in the loop.
array_push() - To put any matching lines into an array. Or, you could just use the $var[] = "string" method.
explode() - To split up your matched lines into an array of words and define an index to return the correct word.

Hope that helped some, I would write a demo script but I can't imagine it being quick to write, plus its nearly midnight here... Give it a go, any problems, post up your script and I'm sure you will be helped.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users