john
john

Reputation: 1273

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

Upvotes: 2

Views: 947

Answers (2)

Brett Gregson
Brett Gregson

Reputation: 5913

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];

Upvotes: 1

marcell
marcell

Reputation: 1528

You can use glob in order to find files. Where $path is the absolute path to your messages directory.

$path = '...';
$files = glob($path . '/*.txt');

foreach ($files as $file) {
    // process your file, put your code here used for one file.
}

Upvotes: 1

Related Questions