网络营销电子商务研究中心

网络营销电子商务研究中心 (https://www.0058.net/index.php)
-   PHP (https://www.0058.net/forumdisplay.php?f=75)
-   -   Best way to get files from a dir filtered by certain extension in php (https://www.0058.net/showthread.php?t=5829)

Kamila 2016-08-16 12:43 AM

Best way to get files from a dir filtered by certain extension in php
 
So right now I have a directory and I am getting a list of files
Code:

$dir_f = "whatever/random/";
$files = scandir($dir_f);

That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.

Karen 2016-08-16 12:45 AM

PHP's glob() function let's you specify a pattern to search for. PHP has a great function to help you capture only the files you need. Its called glob()

glob - Find pathnames matching a pattern
Here is an example usage -
Code:

$files = array();
foreach (glob("/path/to/folder/*.txt") as $file) {
  $files[] = $file;
}


Kasen 2016-08-16 12:47 AM

Code:

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

or

Code:

//path to directory to scan
$directory = "../file/";

//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");

//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array

}


Katelyn 2016-08-16 12:49 AM

8
down vote
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
Code:

$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
or

glob("{$dir}*.{jpg,*​jpeg,gif,ico,png}", GLOB_BRACE). This would work as well for multiple extensions.


All times are GMT +8. The time now is 12:25 AM.

Powered by vBulletin Version 3.8.7
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.