PHP查看每个根目录中的关键字

时间:2017-06-07 18:05:53

标签: php

所以我试了几天才能完成这件事。但我仍然没有一个线索如何构建这个代码,所以它的工作原理。也许有人有个主意。

目标:自动遍历根目录及其任何子目录。如果有一个与关键字匹配的目录,则应将其存储到数组中。

我只是在寻找目录,这就是为什么有一个正则表达式来排除每个带有一个点的名字的对象。还不完美,但这不是问题。

我会发布我的代码的第一个版本。现在它只是在调用时将您处理的目录扫描到函数中。因为我所有的其他尝试都是垃圾,而且这个尝试至少有效

searchformigration('/');


/* Check for related folders, that could be used for a migration */
function searchformigration($dir)
{
    $scanned_elements = scandir($dir);

    for($c = 0; $c <= (count($scanned_elements) - 1); $c++)
    {
        /* Anything but files containing a dot (hidden files, files) */
        if(preg_match('/^[^.]+$/', $scanned_elements[$c]))
        {   
            /* Checking for the keyword "Project" */
            if($scanned_elements[$c] == '*Project*')
            {
                echo $scanned_elements[$c];
                echo '</br>';
            }
            else
            {
                continue;
            }
        }
        else
        {
            continue;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我会以递归方式获取所有目录,然后grep for Project

function searchformigration($dir) {
    $results = glob($dir, GLOB_ONLYDIR);

    foreach($results as $subdir) {
        $results = array_merge($results, searchformigration($subdir));
    }
    return $results;
}

$results = preg_grep('/Project/', searchformigration('/'));

您也可以在Linux上执行此操作:

exec("find / -type d -name 'Project'", $results);

答案 1 :(得分:1)

您可以使用RecursiveDirectoryIterator递归检索文件和文件夹,这将使用&#39; project&#39;在foldername。

print_r(get_dirs('/','project'));


function get_dirs($path = '.', $search='') {

$dirs = array();

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path), 
            RecursiveIteratorIterator::SELF_FIRST);

    foreach ($iterator as $file) {
        if ($file->isDir())
        {

            if (strpos($file->getFileName(), $search) !== false)
            {
                $dirs[] = $file->getRealPath();
            }   
        }
    }

    return $dirs;
}