Jump to content

[SOLVED] Possible? search in txt files and return related lines only


nicob

Recommended Posts

I was wondering if it's possible to search in txt files and return the right lines only.

 

Content of data.txt:

 

one

two

three

four

...

 

When I search for 'three' I get:

three

 

I know there are a lot of search engines scripts, but they work with mysql. So I'm talking about a 'no mysql database required'-script.

 

Ayone?

use fgets() in a loop to get each line from the file separately, and use string comaring/regex functions to find the text you want on each line. add a condition to display/save only the lines that meat certain conditions.

it shouldn't be that bad:

<?php
$fh = fopen("theFile.txt", r); //open the text file for reading
while ($line = fgets($fh)){ //get each line from the file as $line
      //search for a value in the line here with regex or strstr or substr or strcmp
      if (//condition to check if search was successful){
         echo $line; //print the line to screen
         $someVarOrArray = $line; //or you can save the contents of the line to a variable/array for later use.
      }
}
?>

Thank you, wildteen88! a very good script.

question: Can you also link directly to a result? ex. http://www.domain.com/search.php?q=keyword

 

@bobbinsbro

I have noticed that you forgot the "". ;) But it's about the scenario you described.

Thank you, wildteen88! a very good script.

question: Can you also link directly to a result? ex. http://www.domain.com/search.php?q=keyword

Yes that is possible.

 

You have two options.

1. change all instances of $_POST to $_GET and change the forms submit method to get

2. Or just change all instances $_POST to $_REQUEST leaving the form intact. Now you can perform searches from both your form and url.

 

The script is capable of searching for more than one keyword, have a look in page two of the thread.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.