简体   繁体   English

PHP正则表达式查找以_开头的图像

[英]PHP Regular expression to find images beginning with _

I have a function that loads all image files it finds in the wordpress uploads directory. 我有一个函数加载它在wordpress uploads目录中找到的所有图像文件。 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... 我想略微修改它,以便它跳过任何以下划线字符开头的图像,跳过“_someimage.jpg”,而“someimage.jpg不是......

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). 您可以使用strstr (我推荐)修改您当前的正则表达式或添加布尔表达式。

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

substr($file, 0, 1) != '_'
if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 

可以转化为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM