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

时间:2016-02-22 05:36:56

标签: javascript php jquery html ajax

我正在处理一个项目,其中包含.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); 

}


?>
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:0)

在经过SO的代码后,得到了这个。这将通过每个

读取master / sub / folders中的文件
$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;

请检查并澄清。

相关问题