Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex help: Match any image file beginning with an underscore

Tags:

regex

php

The statement below will load all images that do not begin with an underscore character...

if (!is_dir($file) && preg_match("/^[^_].*\.(bmp|jpeg|gif|png|jpg)$/i", $file)) 

I need to modify it so that it only loads images that DO BEGIN with an underscore.

like image 683
Scott B Avatar asked Jan 31 '26 00:01

Scott B


2 Answers

Just remove the negation on the character set: [^_] becomes _:

if (!is_dir($file) && preg_match("/^_.*\.(bmp|jpeg|gif|png|jpg)$/i", $file)) 
like image 84
Alex Brown Avatar answered Feb 02 '26 14:02

Alex Brown


Try glob() to match file pathnames against a pattern, e.g.

glob('_*.{jpg,jpeg,gif,png,bmp}', GLOB_BRACE);

to get all files starting with an underscore and ending in any of the extensions given in the curly braces.

Alternatively, have a look at fnmatch() to check a filename against a pattern.

In addition, if you want to make sure the images are really images, consider checking against the MimeType instead of or in addition to the extension.

like image 33
Gordon Avatar answered Feb 02 '26 15:02

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!