Question

Ok, so I'm trying to list text files in PHP and I need them to contain any number of one variable $words_to_match ='spaghetti' and echo the link. As you can see, the text files are full of strings (or is one string each).

Here is my code:

if($_POST["Confirmed"]=='') 
{
    echo "You need to enter something to search!";
}
else
{
    $path_to_check = 'Confirmed/';
    $words_to_match = $_POST["Confirmed"];//Checks the form from the last page 

    foreach(glob($path_to_check.'*.txt') as $filename)
        {
            foreach(file($filename) as $fli=>$fl) // Not sure what to put here.
                {
                    if (stristr($fl,$words_to_match) !== false) //Or here.
                    {
                        echo '<a href="'.$filename.'">'.$filename.'</a><br />';
                        }
                    }
                }
            }

I'm not sure what to put in the spot that says foreach(file($filename) as $fli=>$fl) Or if (stristr($fl,$words_to_match) !== false). I'm pretty sure the second one is right. When I search for a file containing several lines of spaghetti, it shows several of the same file. If there are 3 lines of spaghetti, there are 3 files -- etc. I just want one of that file listed, even if there is a whole pile of spaghetti in that file. My theory is that it reads the file line by line, and gives an output of all of the lines that have spaghetti in them.

To recap, I want to make it so I have one listed file instead of how many lines contain a string listed as a file.

Any ideas?

BTW, I'm using a standard GoDaddy hosting account with PHP 5.3.

Was it helpful?

Solution

Why not just:

foreach(glob(...) as $filename) {
    if( stripos(file_get_contents($filename),$words_to_check) !== false) {
        // word is present.
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top