我有一堆这样命名的文件...
full-file(1).jpg
full-file(10).jpg
full-file(11).jpg
full-file(12).jpg
full-file(2).jpg
etc...我正在尝试找出使用PHP重命名所有这些文件的最有效的方法,这样它们就可以像这样重命名……
full-file0001.jpg
full-file0010.jpg
full-file0011.jpg
full-file0012.jpg
full-file0002.jpg我已经从一个文件夹中读取了所有文件,并遍历了它们,但不确定去掉括号并使数字4位以0开头的最佳方法。
$image_files = get_files($thumbpath);
foreach($image_files as $index=>$file) {
echo $file;
} 发布于 2012-06-29 19:48:10
使用正则表达式获取数字,然后使用sprintf()对其进行补零
$image_files = get_files($thumbpath);
foreach($image_files as $index=>$file) {
// Capture \d+ into $matches[1]
preg_match('/\((\d+)\)/', $file, $matches);
// Pad it with %04d in sprintf()
$newfile = sprintf("full-file%04d.jpg", $matches[1]);
} 示例:
php > $file = 'full-file(12).jpg';
php > preg_match('/\((\d+)\)/', $file, $matches);
php > $newfile = sprintf("full-file%04d.jpg", $matches[1]);
php > echo $newfile;
// full-file0012.jpg更新(更灵活的文件名):
为了取悦投反对票的人,我只能假设他们想要更灵活的文件名,展开正则表达式:
$image_files = get_files($thumbpath);
foreach($image_files as $index=>$file) {
preg_match('/([^(]+)\((\d+)\)(.+)/', $file, $matches);
$newfile = sprintf("%s%04d%s", $matches[1], $matches[2], $matches[3]);
// And rename the file
if (!rename($file, $newfile)) {
echo "Could not rename $file.\n";
}
else echo "Successfully renamed $file to $newfile\n";
}模式首先匹配,直到使用([^(]+)的第一个(为止的所有内容,然后通过(\d+)匹配数字,其余通过(.*)匹配。
发布于 2012-06-29 19:49:45
可以混合使用REGEXP (去掉括号)和字符串填充(强制四位数字)。
注意:我使用替换回调在一个地方执行这两个操作。
$files = array(
'full-file(1).jpg',
'full-file(10).jpg',
'full-file(11).jpg',
'full-file(12).jpg',
'full-file(2).jpg'
);
function pr_callback($match) {
return str_pad($match[1], 4, '0', STR_PAD_LEFT);
}
foreach($files as $file)
echo preg_replace_callback('/\((\d+)\)/', pr_callback, $file).'<br />';输出:
full-file0001.jpg
full-file0010.jpg
full-file0011.jpg
full-file0012.jpg
full-file0002.jpg
发布于 2012-06-29 21:31:38
我还没看到有人推荐sscanf()。
<?php
$files = array(
"full-file(1).jpg",
"full-file(10).jpg",
"full-file(11).jpg",
"full-file(12).jpg",
"full-file(2).jpg",
);
foreach ($files as $file) {
$n = sscanf($file, "full-file(%d).jpg");
printf("full-file%04d.jpg\n", $n[0]);
}返回:
full-file0001.jpg
full-file0010.jpg
full-file0011.jpg
full-file0012.jpg
full-file0002.jpg当然,只有当"full- file“是您的文件的实际名称时,这才有效。sscanf()不是正则表达式解析器,它只是使用printf()-style格式字符串提取数据...尽管它确实做了一些比http://php.net/sscanf文档更高级的格式识别。如果需要处理其他文件名,可以扩展格式字符串:
<?php
$files = array(
"this-file(1).jpg",
"full-file(10).jpg",
"foo(11).jpg",
"blarg(12).jpg",
"full-file(2).jpg",
);
foreach ($files as $file) {
$n = sscanf($file, "%[a-z-](%d).jpg");
printf("%s%04d.jpg\n", $n[0], $n[1]);
}返回:
this-file0001.jpg
full-file0010.jpg
foo0011.jpg
blarg0012.jpg
full-file0002.jpghttps://stackoverflow.com/questions/11261103
复制相似问题