I’d like to add a regex filter to the script below (just before the array_push) so that, when it encounters files that have the same prefix “_filename” and one of the matches has ‘-150×150.’ at the end of the filename, it pushes that image and skips the others with the same prefix.
However, if there are no images in that collection that have ‘-150×150.’ in the filename, it selects the image with the root prefix (_filename.ext)
For example, if the following files reside in the $dir folder:
_file.png
_file-150x150.png
_file-200x300.png
_someImage.png
_myfile.jpg
_myfile-200x200.jpg
I’d like it to push _file-150×150.png, someImage.png and myfile.jpg into the array, and skip over the others.
$dir = 'wp-content/uploads/';
if(!is_dir($dir)){return;}
$url = get_bloginfo('url').'/wp-content/uploads/';
$imgs = array();
if ($dh = opendir($dir))
{
$myfilter="";
while (($file = readdir($dh)) !== false)
{
if (!is_dir($file)&& $file != "." && $file != ".." && preg_match("/^[".$myfilter."_].*\.(bmp|jpeg|gif|png|jpg)$/i", $file))
{
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
if($imgs)
{
sort($imgs);
echo '<div>';
foreach ($imgs as $idx=>$img)
{
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
echo $prelink.' src="' . $url . $img . '" alt="' .$img . '"' . $class . ' />'.$postlink;
}
echo '</div>';
}
Assuming that the 150×150 filename will always come after the base class, here’s a regex you can use for that:
Explanation:
The result will be something like this: