3

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 advance.

greenbandit
  • 2,267
  • 5
  • 30
  • 44

5 Answers5

9

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.

RDL
  • 7,865
  • 3
  • 29
  • 32
4

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

Ibu
  • 42,752
  • 13
  • 76
  • 103
4

This is what glob() is for:

glob — Find pathnames matching a pattern

Example:

foreach (glob("pic_1*.jpg") as $file)
{
    echo $file;
}
Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • @RDL: Yep was typing lazily and skimming through comments on php.net while you were posting - not copying, thank you for mentioning glob as others have missed, I did give you a vote - wish I could give you three - this glob however will match only .jpgs – Wesley Murch May 11 '11 at 05:20
  • I figured as such. That happens to me all the time too. I just beat you to the punch is all. I gave you a vote up too b/c you are correct. Agreed, I'm surprised how many people don't know about it. – RDL May 11 '11 at 05:22
1

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.

rkg
  • 5,559
  • 8
  • 37
  • 50
1

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

bumperbox
  • 10,166
  • 6
  • 43
  • 66