问题
I'm using following code format to change image name if it already exists on server. I want incremental image names if they already exist with the same name.
Ex: abc.png, abc_1.png, abc_2.png
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 1;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
}
Above code is working if image name is abc.png. If already an image is there on server with name abc_1.png and I run the code it generates image format as abc_1_1.png
.
Expected output:
if already abc_1.png is present and I run the code $newname
should return abc_2.png . How I can achieve it?
回答1:
You just need to check what the string ends with, no need to use a regex for that. Take advantage of weak typing and is_numeric to find the value of any previous counter.
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
// New code here:
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '_')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter + 1;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '_' . $counter . $ext;
$newpath = $path . '/' . $newname;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
}
return $newname;
}
I've simplified the functionality a bit so I could get it into a live example, but If you want to play around with the code in the replacement section that I added you can check it out here: http://ideone.com/xR1v0j Just modify the initial value of $name
to see how it will react to different inputs.
来源:https://stackoverflow.com/questions/34067489/increment-image-name-if-already-exists