开发者

PHP Regular expression to find images beginning with _

I have a function that loads all image files it finds in the wordpres开发者_C百科s 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);
  }


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) != '_'


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜