5

我在这里是一个真正的菜鸟。我想知道是否有人可以给我一段代码,它将查找某个目录中的所有文件以及该目录的子目录以及用户指定的字符串。如果可能限制要搜索的文件类型,例如*.php

我有 99% 可能使用RecursiveDirectoryIteratorpreg_match或者GLOB但我对 php 真的很陌生,并且对这些功能几乎一无所知。

这种代码当然很容易用UNIX命令来完成,但 PHP 我有点卡住了(需要 PHP 而不是 unix 解决方案)。将不胜感激我能从你们那里得到的一切帮助!

编辑:似乎我可能让你们中的一些人感到困惑。我希望该字符串位于文件内部而不是文件名中。

4

3 回答 3

11

你可以很容易地做到这一点。

// string to search in a filename.
$searchString = 'myFile';

// all files in my/dir with the extension 
// .php 
$files = glob('my/dir/*.php');

// array populated with files found 
// containing the search string.
$filesFound = array();

// iterate through the files and determine 
// if the filename contains the search string.
foreach($files as $file) {
    $name = pathinfo($file, PATHINFO_FILENAME);

    // determines if the search string is in the filename.
    if(strpos(strtolower($name), strtolower($searchString))) {
         $filesFound[] = $file;
    } 
}

// output the results.
print_r($filesFound);
于 2013-01-13T08:44:20.843 回答
3

仅在 FreeBSD 上测试...

string在传递目录的所有文件中查找(仅限*nix):

<?php

$searchDir = './';
$searchString = 'a test';

$result = shell_exec('grep -Ri "'.$searchString.'" '.$searchDir);

echo '<pre>'.$result.'</pre>';

?>

仅使用 PHP 在传递的目录中查找string所有文件(不推荐在大量文件中使用):

<?php

$searchDir = './';
$searchExtList = array('.php','.html');
$searchString = 'a test';

$allFiles = everythingFrom($searchDir,$searchExtList,$searchString);

var_dump($allFiles);

function everythingFrom($baseDir,$extList,$searchStr) {
    $ob = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::SELF_FIRST);
    foreach($ob as $name => $object){
        if (is_file($name)) {
            foreach($extList as $k => $ext) {
                if (substr($name,(strlen($ext) * -1)) == $ext) {
                    $tmp = file_get_contents($name);
                    if (strpos($tmp,$searchStr) !== false) {
                        $files[] = $name;
                    }
                }
            }
        }
    }
    return $files;
}
?>

编辑:基于更多细节的更正。

于 2013-01-13T09:22:17.927 回答
2

我找到了一个小文件来搜索文件夹中的字符串:

这里下载文件。

于 2016-03-01T16:02:23.017 回答