Delete files which has the same prefix
Asked Answered
A

2

32
$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?

Activate answered 18/3, 2013 at 3:16 Comment(0)
S
68

Try this code:

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

p.s. glob() requires PHP 4.3.0+

Selfimmolating answered 18/3, 2013 at 3:18 Comment(2)
Hi Shivan, can you please clarify this for me? Does this mean the problem is that unlink() accepts a file name, rather than a file pattern (and hence glob() is required to find all file names based on a pattern)? That all makes sense, but then why did the OP's unlink('*.jpg'); example work OK if patterns are not acceptable to unlink()?Euchromatin
glob() will list out all filenames based on the $mask. By array_map(), the unlink function will load once for each filenames listed by glob().Selfimmolating
V
32

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

foreach (glob("something_prefix*.*") as $filename) {
    unlink($filename);
}
Volkan answered 18/3, 2013 at 3:22 Comment(6)
+1. I find this more readable than the array_map pattern suggested by @ShivanRaptor (and prefer not to use the functional array_map for imperative functions).Euchromatin
@catiel, Shivan Raptor's answer is shorter.Volkan
@Volkan short != better :-)Euchromatin
@Sepster, it's subjective opinion in this case :^ ) I like callbacks.Volkan
@Volkan I totally agree re subjective, and I love callbacks ;-) (Although PHP callbacks kind of bug me as the callable is passed as a literal string and hence wide-open for run-time errors).Euchromatin
I prefer this. Because you can do much in loop.Polky

© 2022 - 2024 — McMap. All rights reserved.