如何在目录中的所有 txt 文件中搜索单词

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

我有一个目录messages,里面有很多txt文件 要在 .txt 文件中搜索单词,我使用此代码:

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

这适用于特定的 .txt 文件。

但是我如何在 所有 目录中搜索 messages 目录中的 txt 文件?

第二个问题:显示找到字符串的txt文件的名称;就像是: Summerevent in 20191110170912.txt

您可以使用 glob 来查找文件。其中 $pathmessages 目录的绝对路径。

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

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

以下应该有效:

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