castiel
castiel

Reputation: 2783

Delete files which has the same prefix

$prefix = 'something_prefix';
unlink($prefix.'.*');

the code above is not working, but I see some code like this below works just fine

unlink('*.jpg');

why? I am wonder is this going to work?

unlink('*.*');

how to delete the files which they begin with the same string? like this

same123.jpg
sametoo.png
samexxx.gif

they all begins with the string "same" but ends with different extension, how to do this?

I alread have a cheap way to do this, but I wonder if there is any better solution?

Upvotes: 32

Views: 20824

Answers (2)

sectus
sectus

Reputation: 15464

You can use glob for this. Something like this(didn't test it):

foreach (glob("something_prefix*.*") as $filename) {
    unlink($filename);
}

Upvotes: 32

Raptor
Raptor

Reputation: 54278

Try this code:

$mask = 'your_prefix_*.*';
array_map('unlink', glob($mask));

p.s. glob() requires PHP 4.3.0+

Upvotes: 68

Related Questions