How to get a list of filtered files using scandir in PHP?

I would like to get all files that have "_img" and the type of PDF in the folder

Instead of using

$fileArray = scandir($dir); foreach ($fileArray as $file) { if (preg_match("_img",$file) && pathinfo($file, PATHINFO_EXTENSION) == 'pdf'){ $filteredArray[] = $file; } } 

Are there short cuts or is this the best way? Thanks

+4
source share
2 answers

Use php glob () function

The glob () function searches for all patterns matching the pattern according to the rules used by the libc glob () function, which is similar to the rules used by common shells

 <?php $filteredArray = array(); foreach (glob($dir."/*_img.pdf") as $filename) $filteredArray[] = $filename; ?> 

There is also a fnmatch () function that matches the file name in the template

The final solution is to use DirectoryIterator with FilterIterator

+2
source

It works great for me. you go into the directory and save it in an array.

At this level, optimization is not required. you win peanuts by losing time to optimize this.

+2
source

Source: https://habr.com/ru/post/1489871/


All Articles