我在使用laravel的时候,需要对一个目录下面的文件进行筛选,例如只想要**.txt**类型的文件。

一种方法是:

Storage::disk('c-drive')->allFiles();

得到文件数组,然后再遍历进行过滤筛选,这种对于文件较多不是很方便,而且比较慢;

第二种方式:使用php自带的glob函数,进行直接筛选;

// List files
$files=glob($path.$match);
foreach($files as $file){
$list[]=substr($file,strrpos($file,"/")+1);
} 

速度快,但是不是很灵活;

第三种方式,比较推荐,使用symfony的Finder包,这个包Laravel本来就自带了,所以直接上方法:

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__);

foreach ($finder as $file) {
    // dumps the absolute path
    var_dump($file->getRealPath());

    // dumps the relative path to the file, omitting the filename
    var_dump($file->getRelativePath());

    // dumps the relative path to the file
    var_dump($file->getRelativePathname());
}

#根据时间,名称来筛选文件
$finder->files()->name('*.php');
use Symfony\Component\Finder\Finder;

$s3 = new \Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper('s3');

$finder = new Finder();
$finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
foreach ($finder->in('s3://bucket-name') as $file) {
    // ... do something with the file
}

 

获取文件真实路径和文件内容:

 dd($file, $file->getRealPath(), $file->getContents());

另外,还可以通过函数直接将文件内容读到一个数组里面去:

实际应用:

 1 public function renameFiles(Request $request)
 2 {
 3     $validator = Validator::make($request->all(), [
 4         'driver' => 'required|in:c-drive, d-drive, e-drive, f-drive',
 5         'dir' => 'required|string|max:1024',
 6         'patten' => 'required|string|max:1024',
 7         'extension' => 'required|string|max:1024',
 8     ]);
 9 
10     if ($validator->fails()) {
11         return $this->outPutJson($validator->errors());
12     }
13 
14     $dir = Storage::disk($driver)->path($dir);
15     $finder = new Finder();
16     $txt = iterator_to_array($finder->files()->name('*\.txt')-            >in($dir));
17     $names = file(head($txt)->getRealPath(),         FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
18     $needs = Finder::create()->files()->name($patten)->in($dir)->depth(0);
19 
20     foreach ($needs as $key => $value) {
21         $a[] = $value->getRealPath();
22     }
23     natsort($a);
24     foreach (array_values($a) as $key => $value) {
25         if (isset($names[$key])) {
26             $res = rename($value, str_replace([' ', '?', '?', ',', ',', '。', ','], '', $dir . '/' . $names[$key] . $extension));
27         } else {
28             dd('这个名字及之后的文件名称未做更改:' . $value . '请注意');
29         }
30     }
31 }                                                    

 

posted on 2019-05-09 14:37  鸥海  阅读(395)  评论(0编辑  收藏  举报