Как искать слова во всех текстовых файлах, которые находятся в каталоге - PullRequest
2 голосов
/ 11 ноября 2019

У меня есть каталог messages, в котором много текстовых файлов. Чтобы найти слово в файле .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-файла, гдестрока найдена;что-то вроде: Summerevent in 20191110170912.txt

Ответы [ 2 ]

1 голос
/ 11 ноября 2019

Должно работать следующее:

$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];
1 голос
/ 11 ноября 2019

Вы можете использовать glob для поиска файлов. Где $path - это абсолютный путь к каталогу messages.

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

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