[英]How can I change a file's extension using PHP?
如何使用 PHP 更改文件的扩展名?
例如:photo.jpg 到 photo.exe
在现代操作系统中,文件名很可能在文件扩展名之前包含很长时间的句点,例如:
my.file.name.jpg
PHP 提供了一种无需扩展名即可查找文件名的方法,考虑到这一点,然后只需添加新扩展名:
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
substr_replace($file , 'png', strrpos($file , '.') +1)
将任何扩展更改为您想要的。 将 png 替换为您想要的扩展名。
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '')
. $info['filename']
. '.'
. $new_extension;
}
在字符串中包含文件名后,首先使用正则表达式将扩展名替换为您选择的扩展名。 这是一个可以做到这一点的小函数:
function replace_extension($filename, $new_extension) {
return preg_replace('/\..+$/', '.' . $new_extension, $filename);
}
然后使用rename()函数用新文件名重命名文件。
只需用正则表达式替换它:
$filename = preg_replace('"\.bmp$"', '.jpg', $filename);
您还可以扩展此代码以删除其他图像扩展名,而不仅仅是 bmp:
$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
对于正则表达式爱好者,Thanh Trung 的“preg_replace”解决方案的修改版本将始终包含新扩展名(这样如果您编写文件转换程序,您不会意外地用结果覆盖源文件)将是:
preg_replace('/\.[^.]+$/', '.', $file) . $extension
更好的方法:
substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension
仅对扩展部分进行更改。 保持其他信息不变。
它是安全的。
您可以使用basename() :
$oldname = 'path/photo.jpg';
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe';
或者对于所有扩展:
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';
最后使用rename() :
rename($oldname, $newname);
已经提出了许多好的答案。 我认为评估和比较他们的表现会很有帮助。 结果如下:
pathinfo
) 的回答耗时 0.000031040740966797 秒。 注意:它的缺点是不包括完整路径。substr_replace
) 的回答耗时 0.000010013580322266 秒。preg_replace
) 的回答耗时 0.00070095062255859 秒。 因此,我建议substr_replace
,因为它比其他的更简单、更快。
请注意,以下解决方案也需要 0.000014066696166992 秒。 仍然无法击败substr_replace
:
$parts = explode('.', $inpath);
$parts[count( $parts ) - 1] = 'exe';
$outpath = implode('.', $parts);
我喜欢strrpos()
方法,因为它非常快速和直接 - 但是,您必须首先检查以确保文件名有任何扩展名。 这是一个 function,它的性能非常好,将替换现有的扩展或添加一个新的扩展(如果不存在):
function replace_extension($filename, $extension) {
if (($pos = strrpos($filename , '.')) !== false) {
$filename = substr($filename, 0, $pos);
}
return $filename . '.' . $extension;
}
我需要它来将所有带有图库的图像扩展名更改为小写。 我最终做了以下事情:
// Converts image file extensions to all lowercase
$currentdir = opendir($gallerydir);
while(false !== ($file = readdir($currentdir))) {
if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {
$srcfile = "$gallerydir/$file";
$filearray = explode(".",$file);
$count = count($filearray);
$pos = $count - 1;
$filearray[$pos] = strtolower($filearray[$pos]);
$file = implode(".",$filearray);
$dstfile = "$gallerydir/$file";
rename($srcfile,$dstfile);
}
}
这对我的目的有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.