BackTrack57
BackTrack57

Reputation: 395

How to search images by name inside a folder?

I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside.

I use this PHP code to display the photos from the whole folder:

$dirname = "photos";
$images = scandir($dirname);
sort($images,SORT_NUMERIC);
krsort($images);
$ignore = Array(".", "..");

foreach($images as $curimg){
    if(!in_array($curimg, $ignore)) {

        echo "<p align=\"center\">Photo $curimg</p>";
        echo "<img class=\"img-responsive\" src=\"". $dirname . '/' . $curimg ."\">";
    }
}

I need some help to adjust my code for it search only photos from the folder that contains inside their name 380,381,382,383,384 or 385.

I think the code below could do it but I don't know how to adjust it with the first code.

$start=380;
$end=385;

for($i=$start; $i<=$end; $i++) {
echo "$i<br>";
}

Upvotes: 1

Views: 4246

Answers (2)

vvye
vvye

Reputation: 1300

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex.

According to the top comment on the docs page, what you could do is something like this:

<?php
    $dirname = "photos";
    $filenames = glob("$dirname/*{380,381,382,383,384,385}*", GLOB_BRACE);

    foreach ($filenames as $filename)
    {
        echo $filename . "<br />";
    }
?>

The GLOB_BRACE options lets you specify a list of values in braces, and the asterisks around them allow those numbers to appear anywhere in the file name. You can then iterate over the returned array and do whatever you want with $filename.

You could use your example for loop to automatically build a string to pass to glob.

Here's the output when I ran this on a test directory I made:

photos/380.zip
photos/asdf382ghj.txt
photos/385.bmp

Note that another file I put in there, a386b.xlsx, didn't match the pattern and doesn't appear on the list.

Upvotes: 1

Alex
Alex

Reputation: 6037

Use the glob() function

 <?php
print_r(glob("*.txt"));
?

The output of the code above could be:

Array
(
[0] => target.txt
[1] => source.txt
[2] => test.txt
[3] => test2.txt
) 

So for your case it could be something like:

$files= glob("38[0-5].jpg");

Upvotes: 1

Related Questions