Php代码,返回一个数组,其中包含包含字符串的文件名


Php code that returns an array with filenames of files which contains a string

我试图创建一个Php文件,该文件不接收任何内容,并检查文件夹中的每个文件,在其中搜索字符串。它会回显一个包含字符串的文件名数组。有没有办法做到这一点,可能是在内存使用率较低的情况下?

非常感谢。

要实现这样的功能,我建议您阅读有关DirectoryTerator类、file_get_contents和PHP中的字符串的信息。

下面是一个示例,说明如何读取给定目录($dir)的内容,并使用strstr在每个文件的内容($contents)中搜索特定的字符串:

<?php
$dir = '.';
if (substr($dir, -1) !== '/') {
    $dir .= '/';
}
$matchedFiles = [];
$dirIterator = new 'DirectoryIterator($dir);
foreach ($dirIterator as $item) {
    if ($item->isDot() || $item->isDir()) {
        continue;
    }
    $file = realpath($dir . $item->getFilename());
    // Skip this PHP file.
    if ($file === __FILE__) {
        continue;
    }
    $contents = file_get_contents($file);
    // Seach $contents for what you're looking for.
    if (strstr($contents, 'this is what I am looking for')) {
        echo 'Found something in ' . $file . PHP_EOL;
        $matchedFiles[] = $file;
    }
}
var_dump($matchedFiles);

这个例子中有一些额外的代码(在$dir中添加一个尾部斜杠,跳过点文件和目录,跳过它本身,等等),我鼓励您阅读和学习。

<?php
$folderPath = '/htdocs/stock/tae';
$searchString = 'php';
$cmd = "grep -r '$searchString' $folderPath";
$output = array();
$files = array();
$res = exec($cmd, $output);
foreach ($output as $line) {
    $files[] = substr($line, 0, strpos($line, ':'));
}
print_r($files);