开发者

finding files in a dir

开发者 https://www.devze.com 2023-03-05 12:13 出处:网络
I have a directory with a lot of files inside: pic_1_79879879879879879.jpg pic_1_89798798789798789.jpg pic_1_45646545646545646.jpg

I have a directory with a lot of files inside:

pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...

I need to list only the pic_1_ files. Any idea how I can do? Thanks in adv开发者_JAVA技巧ance.


Use the glob() function

foreach (glob("directory/pic_1_*") as $filename) {
  echo "$filename";
}

Just change directory in the glob call to the proper path.

This does it all in one shot versus grabbing the list of files and then filtering them.


The opend dir function will help you

$dir ="your path here";

$filetoread ="pic_1_";
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               if (strpos($file,$filetoread) !== false)
                echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
            }
            closedir($dh);
        }
    }

good luck see php.net opendir


This is what glob() is for:

glob — Find pathnames matching a pattern

Example:

foreach (glob("pic_1*.jpg") as $file)
{
    echo $file;
}


Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.


This is one of the samples from the manual

http://nz.php.net/manual/en/function.readdir.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

you can modify that code to test the filename to see if it starts with pic_1_ using something like this

if (substr($file, 0, 6) == 'pic_1_')

Manual reference for substr

http://nz.php.net/manual/en/function.substr.php

0

精彩评论

暂无评论...
验证码 换一张
取 消