1

I have a directory of images on a server that customers have uploaded. I need to be able to get all files that match a certain string or item code and put them inside an array. Filenames and extensions can always vary but each file will always have an 8 digit item code in the filename. So for instance say in my directory i have:

/images/

62115465.jpg
62115465-02.jpg
62115465-07.jpg
13452766.png
56773392.jpeg
56773392-avatar.jpg

I want to be able to pull out all the files that match the 8 digit item code so:

//all images that have 62115465 in the file name would give me

62115465.jpg
62115465-02.jpg
62115465-07.jpg

//or all images that have 56773392 in the file name would give me

56773392.jpeg
56773392-avatar.jpg

and then want them in an array like so:

$all_files = array(
  '62115465.jpg',
  '62115465-02.jpg',
  '62115465-07.jpg'
);

I tried using the glob() function as below which can match some files like the 62115465.jpg but doesnt pick up the 2 other files with the -02 and -07 tags

$files = glob('62115465.'.*');
2
  • 1
    Did you try removing the .? Commented Nov 26, 2013 at 14:11
  • This should sort it for you, $files = glob('62115465*.*'); it will match anything starting with the number and with any ext. Commented Nov 26, 2013 at 14:12

4 Answers 4

3
glob('62115465*');

note the removal of the .. glob() essentially replicates doing something like dir *.txt at a command prompt.

Sign up to request clarification or add additional context in comments.

Comments

2

I know this question was answered already, but to the novice/intermediate coder, or anyone new to the glob() function (AHEM ME COUGH), it's pretty unclear what's going on here. So, here's a full script that I cobbled together to do pretty much the same thing the OP asked for- search through a directory for all files beginning with the target prefix and add them to an array.:

<?php
$imgs = array();
$dir =  $_SERVER['DOCUMENT_ROOT'].'/path/to/your/images';
$prefix = 'your-prefix_string-_-';
chdir($dir);
$matches = glob("$prefix*");
if(is_array($matches) && !empty($matches)){
    foreach($matches as $match){
        $imgs[] = $match;
    }
}
?>

Comments

0

Can you try this,

 $files = glob('62115465.*');

Comments

0

Try like this-

$files = glob("[^62115465]*.*);

Or like this:

$files = glob("62115465*.*);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.