简体   繁体   English

帮助全球模式

[英]help with glob pattern

It would be nice if someone could give me a regexp pattern for glob for getting below filenames: 如果有人可以给我一个glob的正则表达式模式以获取低于文件名的方法,那就太好了:

1.jpg // this file
1_thumb.jpg
2.png // this file
2_thumb.png
etc...

returning the files without "_thumb". 返回没有“ _thumb”的文件。 I have this pattern: 我有这种模式:

$numericalFiles = glob("$this->path/*_thumb.*");

and that give me all with "_thumb." 那给我所有人以“ _thumb”。

glob() isn't the greatest at handling situations where you have complex requirements for file matching, as you've clearly noticed. 正如您已经明显注意到的那样, glob()在处理对文件匹配有复杂要求的情况下并不是最出色的。 I'd recommend using PHP's SPL library and taking advantage of the DirectoryIterator class. 我建议使用PHP的SPL库并利用DirectoryIterator类。

$iterator = new DirectoryIterator("/dir/path");
foreach ($iterator as $file) {
    if ($file->isFile() && preg_match("/^[0-9]+\./i",$file->getFilename())) {
        echo $file->getFilename();
    }
}

You can modify your criteria cleanly during the iteration (also, it's easy to modify the iterator if you ever needed recursive directory iteration ). 您可以在迭代过程中干净地修改条件(而且,如果需要递归目录迭代 ,很容易修改迭代器)。

Glob patterns and regular expressions are different. 球形模式和正则表达式不同。 But PHP's glob implementation does not implement the pattern negation required for matching just those files. 但是PHP的glob实现不能实现仅匹配那些文件所需的模式求反。 You will need to use a larger positive pattern such as [0-9]*.jpg and then filter the results afterwards. 您将需要使用较大的正数图案,例如[0-9]*.jpg ,然后再过滤结果。

foreach (glob('[0-9]*') as $filename) {
    if (strpos("$filename","_thumb") === FALSE){
        echo "$filename \n";
    }
}

Further to zombat's use of the DirectoryIterator, it might also make sense to construct your own specialized filter class to make life easier (see the difference with the foreach loops) and more reusable. 除了zombat使用 DirectoryIterator之外,构造自己的专用过滤器类也可能很有意义,以使生活更轻松(请参见foreach循环的区别)并更可重用。

class DirectoryFilterThumbs extends FilterIterator {
    public function __construct($path) {
        parent::__construct(new DirectoryIterator($path));
    }
    public function accept() {
        // Use regex or whatever you like here
        return ($this->isFile() && strpos($this->getFilename(), "_thumb.") === FALSE);
    }
}

$files = new DirectoryFilterThumbs("/dir/path");
foreach ($files as $file) {
    echo $file->getFilename() . PHP_EOL;
}

Of course, if there is no need to do this in multiple places then the plain DirectoryIterator/condition combo given by zombat is perfectly suitable. 当然,如果不需要在多个位置执行此操作,则zombat提供的普通DirectoryIterator / condition组合非常适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM