PHP Regular expression to search for images starting with _

I have a function that downloads all image files found in the wordpress download directory. I would like to modify it a bit so that it skips any image starting with an underscore, "_someimage.jpg" is skipped, and "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);
  }
+3
source share
2 answers

You can change the current regex or add a boolean with strstr (which I would recommend).

Change the current regular expression:

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

Or a simple expression to detect underscores in a string:

strstr($file, '_')

edit: substr:

substr($file, 0, 1) != '_'
+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)) 
0

Source: https://habr.com/ru/post/1729744/


All Articles