我在使用laravel的时候,需要对一个目录下面的文件进行筛选,例如只想要**.txt**类型的文件。
Storage::disk('c-drive')->allFiles();
得到文件数组,然后再遍历进行过滤筛选,这种对于文件较多不是很方便,而且比较慢;
// List files
$files=glob($path.$match);
foreach($files as $file){
$list[]=substr($file,strrpos($file,"/")+1);
}
速度快,但是不是很灵活;
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());
参考链接:
https://secure.php.net/manual/en/function.iterator-to-array.php
https://symfony.com/doc/current/components/finder.html
另外,还可以通过函数直接将文件内容读到一个数组里面去:
public function renameFiles(Request $request)
{
$validator = Validator::make($request->all(), [
'driver' => 'required|in:c-drive, d-drive, e-drive, f-drive',
'dir' => 'required|string|max:1024',
'patten' => 'required|string|max:1024',
'extension' => 'required|string|max:1024',
]);
if ($validator->fails()) {
return $this->outPutJson($validator->errors());
}
$dir = Storage::disk($driver)->path($dir);
$finder = new Finder();
$txt = iterator_to_array($finder->files()->name('*\.txt')->in($dir));
$names = file(head($txt)->getRealPath(), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$needs = Finder::create()->files()->name($patten)->in($dir)->depth(0);
// dd($needs);
foreach ($needs as $key => $value) {
// dd($value->getExtension());
$a[] = $value->getRealPath();
}
natsort($a);
$a = array_values($a);
// dd($a);
foreach ($a as $key => $value) {
// dd($a, $names);
if (isset($names[$key])) {
$res = rename($value, str_replace([' ', '?', '?', ',', ',', '。', ','], '', $dir . '/' . $names[$key] . $extension));
} else {
dd('这个名字及之后的文件名称未做更改:' . $value . '请注意');
}
}
}
参考函数:
glob — 寻找与模式匹配的文件路径