Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在目录中的所有txt文件中搜索单词_Php_Search_Fopen - Fatal编程技术网

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

Php 如何在目录中的所有txt文件中搜索单词,php,search,fopen,Php,Search,Fopen,我有一个目录messages,里面有很多txt文件 要在.txt文件中搜索单词,我使用以下代码: $searchthis = "Summerevent"; $matches = array(); $handle = @fopen("messages/20191110170912.txt", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle); if(strp

我有一个目录
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文件很有效

但是我如何在目录
消息
中的所有txt文件中搜索呢

第二个问题:显示找到字符串的txt文件的名称;比如: 您可以使用20191110170912.txt中的Summerevent查找文件。其中,
$path
是指向
邮件
目录的绝对路径

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