gpt4 book ai didi

php - 在php中递归搜索所有目录中的字符串数组

转载 作者:行者123 更新时间:2023-12-03 01:25:56 24 4
gpt4 key购买 nike

我是 PHP 编码新手,这里正在寻找在所有目录中递归搜索字符串数组的最快方法。

我就是这样做的

$contents_list = array("xyz","abc","hello"); // this list can grow any size
$path = "/tmp/"; //user will give any path which can contain multi level sub directories

$dir = new RecursiveDirectoryIterator($path);

foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
echo $line."\n";
}
}
}
}
fclose($fd);
}

在这里,我递归地迭代所有目录,然后再次在每个文件上迭代内容数组以进行搜索。

有没有更好的方法来进行搜索?请建议更快的替代方案。

谢谢

最佳答案

如果您被允许在您的环境中执行 shell 命令(并假设您在 *nix 上运行脚本),您可以递归调用 native grep 命令。这将为您提供最快的结果。

$contents_list = array("xyz","abc","hello");
$path = "/tmp/";
$pattern = implode('\|', $contents_list) ;
$command = "grep -r '$pattern' $path";
$output = array();
exec($command, $output);
foreach ($output as $match) {
echo $match . '\n';
}

如果 disable_functions 指令有效并且您无法调用 grep,您可以使用 RecursiveDirectoryIterator 的方法并使用 strpos 逐行读取文件每行。请注意,strpos 需要严格的相等性检查(使用 !== false 而不是 != false),否则您将跳过以下位置的匹配:一行的开头。

稍微快一点的方法是递归地使用 glob 来获取文件列表,并立即读取这些文件,而不是逐行扫描它们。根据我的测试,这种方法将为您带来大约 30-35% 的时间优势。

function recursiveDirList($dir, $prefix = '') {
$dir = rtrim($dir, '/');
$result = array();

foreach (glob("$dir/*", GLOB_MARK) as &$f) {
if (substr($f, -1) === '/') {
$result = array_merge($result, recursiveDirList($f, $prefix . basename($f) . '/'));
} else {
$result[] = $prefix . basename($f);
}
}

return $result;
}

$files = recursiveDirList($path);
foreach ($files as $filename) {

$file_content = file($path . '/' . $filename);
foreach ($file_content as $line) {
foreach($contents_list as $content) {
if(strpos($line, $content) !== false) {
echo $line . '\n';
}
}
}
}

递归 glob 函数的功劳为 http://proger.i-forge.net/3_ways_to_recursively_list_all_files_in_a_directory/Opc

总而言之,在性能方面,您有以下排名(使用两种常见的文本模式,对于包含约 1200 个文件的非常大的目录,在几秒钟内得到结果):

  1. 通过 exec() 调用 grep - 2.2015s
  2. 使用递归glob并使用file()读取文件 - 9.4443s
  3. 使用RecursiveDirectoryIterator并使用readline()读取文件 - 15.1183s

关于php - 在php中递归搜索所有目录中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com