suncat100 suncat100 - 1 year ago 91
PHP Question

PHP regex ignore files that start with double __underscore

I have tried, but I simply can't wrap my head around regex in PHP. I need a regex that does the following:

  • ignores files that start with double __underscore. (for example __file.jpg)

  • ignores files that end with "thumb". (for example somethumb.jpg or thumb.jpg)

  • ignores all file types but gif|jpg|png|jpeg

I have the following for now, which seems to fulfill #2 and #3, but not #1:

preg_match(/(?<!thumb)\.(gif|jpg|png|jpeg)$/i, $file)

Any help much appreciated!

Answer Source

If I understood third point correctly it means that it should end with all these file extensions. Considering this, the following will work

1st Solution


Regex Demo

Towards an efficient solution

2nd Solution


3rd Solution (suggested by Wiktor in comments)


4th Solution (suggested by Casimir in comments)


PHP Code

$re = "/^(?!__|.*thumb\\.(?:gif|jpg|png|jpeg))(?=.*\\.(?:gif|jpg|png|jpeg)$)(.*)/m";
$str = "__abcd.jpg\nthumbabcd.gif\nthumbabcdthumb.jpg\nthumbs.jpg\nsomethumb.jpg\nthumb.jpg\nabcd.jpg\nabcd.jps"; 

preg_match_all($re, $str, $matches);

Ideone Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download