PHP增量文件名

时间:2012-02-21 19:46:29

标签: php filenames

我有这个检查文件名的功能。如果存在,则按照这种模式将其递增1:

image.jpg
image1.jpg
image2.jpg

问题出现在第4张图片上,它带有0.jpg

以下是相关代码:

...
$filetarget = $this->make_image_filename($directory, $new_filename, $extension);

if(!move_uploaded_file($file['tmp_name'], $filetarget)){
    $error[$index] = 'copy';
}
...

private function make_image_filename($directory, $name = '', $extension){
    if(empty($name)) $name = 'NULL';
    $filetarget = $directory.$name.$extension;

    if(file_exists($filetarget)){
        $name = $this->increment_filename($name);

        return $this->make_image_filename($directory, $name, $extension);
    } else {
        return $filetarget;
    }
}


private function increment_filename($name){

    $index = $this->get_filename_index($name);

    if(is_numeric($index)){
        $pos = strpos($name, $index);
        $name = substr($name, 0, $pos);
    }

    if(is_null($index)){
        $index = 0;
    }

    ++$index;

    return $name.$index;
}

private function get_filename_index($name){
    // CHECK FOR INDEX
    $i = 1;
    $index = substr($name, -$i);
    $last_chars = substr($name, -$i);

    while(is_numeric($last_chars)){
        ++$i;
        $last_chars = substr($name, -$i);
        if(is_numeric($last_chars)){
            $index = $last_chars;
        }
    }

    if(is_numeric($index)){
        return $index;
    } else {
        return NULL;
    }
}

我现在正在将我的本地服务器上的代码隔离以运行一些测试。你能否在这个过程中看到任何固有的缺陷?

2 个答案:

答案 0 :(得分:1)

这是我用来做同样事情的函数:

function make_unique($full_path) {
    $file_name = basename($full_path);
    $directory = dirname($full_path).DIRECTORY_SEPARATOR;

    $i = 2;
    while (file_exists($directory.$file_name)) {
        $parts = explode('.', $file_name);
        // Remove any numbers in brackets in the file name
        $parts[0] = preg_replace('/\(([0-9]*)\)$/', '', $parts[0]);
        $parts[0] .= '('.$i.')';

        $new_file_name = implode('.', $parts);
        if (!file_exists($new_file_name)) {
            $file_name = $new_file_name;
        }
        $i++;
    }
    return $directory.$file_name;
}

(除了它使文件名像image(1).jpg image(2).jpg

答案 1 :(得分:0)

这个怎么样:

function get_next_file_name($file) {
    if (!preg_match('/^(\D+)(\d*)(\.\S+)$/', $file, $match)) {
        throw new Exception('bad file name format');
    }
    return $match[1] . (empty($match[2]) ? 1 : ($match[2] + 1)) . $match[3];
}
echo get_next_file_name('image.jpg'), "\n";      // prints image1.jpg
echo get_next_file_name('image1.jpg'), "\n";     // prints image2.jpg
echo get_next_file_name('image999.jpg'), "\n";   // prints image1000.jpg