PHP重命名文件名如果存在附加数字结束

PHP重命名文件名如果存在附加数字结束

本文介绍了PHP重命名文件名如果存在附加数字结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重命名图像的文件名称,如果它存在,说如果我的文件名是 test.jpg ,它已经存在我想将其重命名为 test1.jpg ,然后 test2.jpg 等等。随着代码我已经写了它改变我的文件名如 test1.jpg ,然后 test12.jpg 任何建议在修复这将是非常感谢!



PHP

  $ name = $ _FILES ['picture'] ['name']; 
$ actual_name = pathinfo($ name,PATHINFO_FILENAME);
$ extension = pathinfo($ name,PATHINFO_EXTENSION);

$ i = 1;
while(file_exists('tmp /'.$ actual_name。。。$ extension))
{
$ actual_name =(string)$ actual_name。$ i;
$ name = $ actual_name。。。$ extension;
$ i ++;

$ / code $ <$ $ p

解决方案

认为应该做你想做的:

$ p $ $ actual_name = pathinfo($ name,PATHINFO_FILENAME);
$ original_name = $ actual_name;
$ extension = pathinfo($ name,PATHINFO_EXTENSION);

$ i = 1;
while(file_exists('tmp /'.$ actual_name。。。$ extension))
{
$ actual_name =(string)$ original_name。$ i;
$ name = $ actual_name。。。$ extension;
$ i ++;
}


I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!

PHP

$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
    $actual_name = (string)$actual_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
}
解决方案

Here's a minor modification that I think should do what you want:

$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
    $actual_name = (string)$original_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
}

这篇关于PHP重命名文件名如果存在附加数字结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:35