Scott B
Scott B

Reputation: 40157

PHP Regular expression to find images beginning with _

I have a function that loads all image files it finds in the wordpress uploads directory. I'd like to modify it slightly so that it skips over any image that begins with an underscore character, "_someimage.jpg" is skipped, while "someimage.jpg is not...

Here is the existing function....

 $dir = 'wp-content/uploads/';
 $url = get_bloginfo('url').'/wp-content/uploads/';
 $imgs = array();
  if ($dh = opendir($dir)) 
  {
  while (($file = readdir($dh)) !== false) 
   {
   if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 
   {
   array_push($imgs, $file);
   }
  }
  closedir($dh);
  } else {
   die('cannot open ' . $dir);
  }

Upvotes: 3

Views: 536

Answers (2)

tur1ng
tur1ng

Reputation: 3309

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

could be transformed into:

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

Upvotes: 0

Mark Elliot
Mark Elliot

Reputation: 77044

You can modify your current regex or add an boolean expression using strstr (which I'd recommend).

Modifying your current regex:

"/^[^_].*\.(bmp|jpeg|gif|png|jpg)$/i"

Or a simple expression to detect underscores in the string would be:

strstr($file, '_')

edit: and actually you could use substr:

substr($file, 0, 1) != '_'

Upvotes: 1

Related Questions