Aero Wang
Aero Wang

Reputation: 9217

How to use PHP to get all the image filenames except containing certain words?

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?

Upvotes: 1

Views: 78

Answers (2)

username tbd
username tbd

Reputation: 9382

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.

Upvotes: 2

hwnd
hwnd

Reputation: 70722

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)));

Upvotes: 3

Related Questions