Increment image name if already exists

走远了吗. 提交于 2019-12-11 09:51:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!