从 PHP 动态上传的目录中存在的.txt文件中查找关键字

Finding a Keyword from a .txt file present in directories uploaded dynamically in PHP

本文关键字:存在 txt 文件 关键字 查找 动态 PHP      更新时间:2023-09-26

我正在做一个项目,其中包括一个.tar文件将被上传到UI,它将通过脚本解析并解压缩 现在这个捆绑包将包含许多文件夹,我需要单独访问每个文件夹并在其中搜索.txt文件以获取关键字,以便它将包含关键字的整行显示在UI上。

有以下脚本,我正在使用该脚本在文件夹内的不同.txt文件中搜索关键字,但是当有多个文件夹并且需要访问单独的文件夹并显示来自不同文件夹的文件.txt关键字时,逻辑无法正常工作

<?php
$searchfor = $_GET['keyword'];
$file = array('alert_tool.INFO','alert_manager.INFO');
foreach($file as $name)
{
echo "'n"; echo"'n";
$contents = file_get_contents($name);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*'$/m";
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:<br />";
   echo implode("<br /> $name", $matches[0]);
}
else{
for ($i = 0; $i < 2; $i++)
{
   echo nl2br ("'n'n'n'n'n No matches found in $file[$i]");
}
}
@fclose ($file); 
}
?>

任何帮助都非常感谢。谢谢。

在通过 SO 这里的代码后,得到了这个。这将读取主/子/文件夹中的文件

$searchfor = $_GET['keyword'];
$path = 'master-folder';
$dirs = array();
// directory handle
$dir = dir($path);
//This will have all the sub directories within the master-folder
while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $path . '/' .$entry."/"; 
       }
    }
}
//echo "<pre>"; print_r($dirs); exit; 

// This foreach is to read each sub folders inside the master-folder
foreach($dirs as $directory):
    //$linesToReturn = 4; // Set to four for the number of lines in each text file ( for expansion? )
    // Find all files in the directory which are .xyz files
    foreach( glob( $directory . "*.INFO" ) as $filename )
    {
        //echo $filename;
        // Open the file
        if( $handle = @fopen( $filename, "r") )
        {
            $x = 0; // Start the line counter
            // Cycle each line until end or reach the lines to return limit
            while(! feof( $handle ) )
            {
                $contents = fgets($handle); // Read the line
                // then match your search with the contents
                $x++; // Increase the counter
            }

        }
    }
endforeach;

请检查并澄清。