Search code examples
phpregexglob

How to use glob to find thumbnails


Say I upload a file called myimage.jpg and I generate thumbnails of this image that append width x height to the filename. I might have a directory of images that looks like this:

myimage.jpg
myimage-100x50.jpg
myimage-500x250.jpg
myimage-430x300.jpg

When I want to delete this image I need to delete all of the thumbs as well. ow would I use glob to find the original image and all of the thumbnails but not any other images that may be in the directory?


Solution

  • I did this in the end:

    // find all images that match the filename
    foreach (glob(myimage.*) as $filename) {
    
        // use regex to filter out any that have a similar name and are not thumbs
        if(preg_match("/(\myimage-\b)[0-9]\d*x[0-9]\d*(\b.jpg\b)/", $filename)) {
    
            // delete the thumb
            unlink($filename);
        }
    }
    
    // delete the original image
    unlink(myimage.jpg);