1

I like to use PHP to get all the filenames in a directory except if the filename contains a certain word, for example "thumbnail".

This is how I get all the image filenames:

$images = glob($imagesDir . $albumName . '/' . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

So I tried:

$images = glob($imagesDir . $albumName . '/' . '^(?!thumbnail$).*.{jpg,jpeg,png,gif}', GLOB_BRACE);

Apparently it would not return anything. I am not familiar with regular expression in PHP. Did I do something wrong?

Aero Wang
  • 8,382
  • 14
  • 63
  • 99

2 Answers2

3

Using preg_grep() you can use regular expression to exclude files that contain "thumbnail" ..

$images = array_values(preg_grep('/^(?!.*thumbnail).*$/', glob($imagesDir . $albumName . '/' . '*.{jpg,jpeg,png,gif}', GLOB_BRACE)));
hwnd
  • 69,796
  • 4
  • 95
  • 132
2

Regular expressions that only match strings not containing words can be a bit difficult, and often inefficient too. Using a combination of regex and PHP might be the best option for you. Something like this should do:

$images = glob($imagesDir . $albumName . '/' . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$images = array_filter($images, function($s) { return strpos($s,'thumbnail') === false; });

Also, my sincerest apologies for making the first part of my answer rhyme more than intended.

Community
  • 1
  • 1
username tbd
  • 9,152
  • 1
  • 20
  • 35
  • Hi I tried this method and when I echo $images, I still get thumbnail.jpg. I suspect that is because I haven't update the new filtered $images. If so, how do I accomplish that? – Aero Wang Jul 17 '14 at 08:49
  • @AeroWindwalker ah, my apologies—I just edited it, that version should work for you. – username tbd Jul 17 '14 at 08:51