Checking for file-extensions in PHP with Regular expressions

I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.

Both capital and small letters. Those are the only files to be accepted.

I am currently using this:

$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)");

and the function takeFiles looks like this:

function takerFiles($dir, $rex="") {
    $dir .= "/";
    $files = array();
    $dp = opendir($dir);
    while ($file = readdir($dp)) {
      if ($file == '.')  continue;
      if ($file == '..') continue;
      if (is_dir($file)) continue;
      if ($rex!="" && !preg_match($rex, $file)) continue;
      $files[] = $file;
    }
    closedir($dp);
    return $files;
  }

And it always returns nothing. So something must be wrong with my regex code.

Answers


I think something is wrong with your regex. Try testing regexes here first: http://www.spaweditor.com/scripts/regex/index.php

I think this one might work for you:

/^.*\.(jpg|jpeg|png|gif)$/i

Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)


Need Your Help

Create so instead of dylib using nar maven plugin

c osx maven maven-nar-plugin pljava

I now have pljava building on the Mac. pljava uses maven and the maven nar plugin for building. This maven nar build is currently creating a dylib instead of a .so. It looks like that postgres wan...

PHP Is there any better way to create this new array?

php arrays key

for ($i = 0; $i < count($keyListArray); $i++) {