Search code examples
phpsearchfopen

How to search for words in all txt files which are in a directory


I have a directory messages in which a lot of txt files To search for a word in a .txt file, i use this code:

$searchthis = "Summerevent";
$matches = array();

$handle = @fopen("messages/20191110170912.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
echo $matches[0];

This works fine for the specific .txt file.

But how can i search in all the txt files which are in the directory messages ?

And second question: show the name of the txt file where the string is found; something like: Summerevent in 20191110170912.txt


Solution

  • The following should work:

    $searchthis = "Summerevent";
    $matches = array();
    
    $files = glob("messages/*.txt"); // Specify the file directory by extension (.txt)
    
    foreach($files as $file) // Loop the files in our the directory
    {
        $handle = @fopen($file, "r");
        if ($handle)
        {
            while (!feof($handle))
            {
                $buffer = fgets($handle);
                if(strpos($buffer, $searchthis) !== FALSE)
                    $matches[] = $file; // The filename of the match, eg: messages/1.txt
            }
            fclose($handle);
        }
    }
    
    //show results:
    echo $matches[0];