Search code examples
phpfileunlink

How can I delete all files in a folder, which matches a certain pattern?


I have a folder with images.

As example:

z_1.jpg
z_2.jpg
z_3.jpg
//...

I want to delete every image with prefix z_*.jpg. How can I do that?

unlink('z_*.jpg'); ?

Solution

  • You need the exact filename to unlink() a file. So just use glob() to get all files which you want to grab. Loop through the returned array and delete the files, e.g.

    <?php
    
        $files = glob("z_*.jpg");
    
        foreach($files as $file)
            unlink($file);
    
    ?>