PHP:如何在文件输出中使用字符串生成索引名称


PHP: How to generate indexed name with string in file output?

实际上我使用的是uniqid();生成随机名称:

$file = UPLOAD_DIR . uniqid() . '.png';

输出如下:

53bd02cdc6b9b.png
53bd02cdc6bd8.png
53bd0320aafbc.png
53bd0320aaff7.png
53bd03e89b8df.png

我想更改每个文件的名称作为输出:

picture_0001.png
picture_0002.png
picture_0003.png
picture_0004.png
picture_0005.png
你有更好的主意吗?

您想要将所有当前图像固定为正确的格式(参见@ flix Gagnon-Grenier回答),然后一旦您完成了,您可以做以下操作:

//get array of current images
$imgs = glob(UPLOAD_DIR.'*.png');
//select last image in array, strip out all non-alpha's then pad it with 4 0's
$next = str_pad(preg_replace("/[^0-9]/","", end($imgs))+1, 4, "0", STR_PAD_LEFT);
$file = UPLOAD_DIR.'picture_'.$next.'.png';

编辑

参见注释-基于文件的计数器

$count_file = UPLOAD_DIR.'count.txt'; //or put somewhere else
//make count file if not exists
if(!file_exists($count_file)){
    file_put_contents($count_file,0);
}
//get last image count + 1 
$next = file_get_contents($count_file)+1;
//set file var 
$file = UPLOAD_DIR.'picture_'.sprintf("%04s",$next).'.png';
//update counter
file_put_contents($count_file, $next);

好吧,既然它伤害了你的感情,你似乎是一个人,而我关心人类。给你:

我不知道任何上下文,所以这可能与您实际需要的相差甚远。

说目录是/home/dir

$i = 1;
foreach (scandir('/home/dir') as $file)
 {if ($file == '.' || $file == '..') continue;
  rename($file,'picture_' . str_pad($i,4,'0',STR_PAD_LEFT) . '.png');
  $i++;}

这将生成:

picture_0001.png
picture_0002.png
picture_0003.png
picture_0004.png
picture_0005.png

替换旧文件