【问题标题】:Symfony Finder: Finding all directories except ones that start with an underscoreSymfony Finder:查找所有目录,但以下划线开头的目录除外
【发布时间】:2014-12-16 12:09:43
【问题描述】:

我想查找所有不以下划线开头的目录(在根级别,非递归)。

getcwd() = /Users/example/project

目录示例:

/Users/example/project/_pictures
/Users/example/project/_graphics
/Users/example/project/test

我已经尝试使用以下代码 sn-p:

$directories = $this->container->get('finder')
    ->directories()
    ->in(getcwd())
    ->notName('_*')
    ->depth(0);

但这似乎又回来了:

/Users/example/project/_pictures/home
/Users/example/project/test

所以它返回“test”,这是正确的,但它也返回一个以下划线开头的子文件夹,这是不正确的。任何想法这里出了什么问题?

【问题讨论】:

  • 您的代码似乎可以正常工作,请确保您使用的是最新版本并设置深度->depth(0);

标签: php regex symfony finder


【解决方案1】:

这行得通:

$directories = glob(getcwd() . '/[!^_]*', GLOB_ONLYDIR);

但希望使用 Symfony finder 找到解决方案。

【讨论】:

    【解决方案2】:

    我在Finder::searchInDirectory找到:

    if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
        $this->notPaths[] = '#(^|/)\..+(/|$)#';
    }
    

    用这个修改它就可以了:)

    $finder->notPath('#(^|/)_.+(/|$)#')
    

    更新

    这是我的代码:

    $finder = Finder::create()
        ->files()
        ->name('*.twig')
        ->notPath('#(^|/)_.+(/|$)#') // Ignore path start with underscore (_).
        ->ignoreVCS(true)
        ->ignoreDotFiles(true)
        ->ignoreUnreadableDirs()
        ->in(__DIR__);
    
    foreach ($finder as $file) {
        var_dump($file->getRelativePath());
    }
    

    【讨论】:

    • 您能否将您的$finder->notPath('#(^|/)_.+(/|$)#') 代码集成到OPs 代码中作为如何实现它的示例?确保您准确指出字符串如何影响输出。请务必注意字符排除的内容是否超出了 OP 的要求。
    【解决方案3】:

    尝试使用 $finder->exclude($dirs);

    【讨论】:

    • 我尝试查找所有下划线目录,然后将它们添加到排除方法,但它也没有工作。我确信必须有一个正则表达式可以添加到 notName() 中,这样也会更快。
    • notPath($pattern) 呢?
    • 如果我做路径,那么它将尝试整个路径上的模式,而不是实际的目录名称本身,这将变得不必要地复杂。
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多