我正在开发一个项目,其中包含一个 .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/