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

标签 javascript php jquery html ajax

我正在开发一个项目,其中包含一个 .tar 文件,该文件将上传到 UI,它将由脚本解析并解压。现在该 bundle 将包含许多文件夹,我需要单独访问每个文件夹并搜索 .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); 

}


?>

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

最佳答案

在浏览完这里的代码后,得到了这个。这将按每个读取 master/sub/文件夹内的文件

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

请检查并澄清。

关于javascript - 从 PHP 动态上传的目录中存在的 .txt 文件中查找关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35546459/

相关文章:

php - 无法连接到 graph.facebook.com 端口 443 : Network unreachable

javascript - 如何使用 JQuery 从相对元素获取 html 文本?

javascript - jQuery Ajax 问题...如何通过一次 ajax 调用更新两个 DIV?

javascript - ReactJS Onclick 不适用于生成的元素

javascript - HighCharts:鼠标点击事件由 Series 处理程序和 Point 处理程序处理

php - 这是 WordPress 中的 .htaccess 代码。有人可以解释它是如何工作的吗?

php - 如何在 laravel 的编辑 View 中更新图像?

javascript - 将数据发送到jquery中已经有数据的li

javascript - 处理嵌套上下文提供程序

javascript - Putty 窗口关闭时,机器人将关闭