php 更改文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1724612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:37:47  来源:igfitidea点击:

Change file extension

php

提问by Ivan Nevostruev

How do I change a files file-extension name in PHP?

如何在 PHP 中更改文件文件扩展名?

For example: $filename='234230923_picture.bmp'and I want the extension to change to jpg.

例如:$filename='234230923_picture.bmp'我希望扩展名更改为jpg.

回答by gnud

$newname = basename($filename, ".bmp").".jpg";
rename($filename, $newname);

Remember that if the file is a bmp file, changing the suffix won't change the format :)

请记住,如果文件是 bmp 文件,更改后缀不会更改格式:)

回答by Ivan Nevostruev

Just replace it with regexp:

只需用正则表达式替换它:

$filename = preg_replace('"\.bmp$"', '.jpg', $filename);

You can also extend this code to remove other image extensions, not just bmp:

您还可以扩展此代码以删除其他图像扩展名,而不仅仅是bmp

$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);

回答by Rob

rename()the file, substituting the new extension.

rename()文件,替换新的扩展名。

回答by Tim Lytle

Not using regex (like the basename example), but allowing multiple extension possibilities (like the regex example):

不使用正则表达式(如 basename 示例),但允许多种扩展可能性(如正则表达式示例):

$newname = str_replace(array(".bmp", ".gif"), ".jpg", $filename);
rename($filename, $newname);

Of course any simple replace operation, while less expensive then regex, will also replace a .bmp in the middle of the filename.

当然,任何简单的替换操作虽然比正则表达式便宜,但也会替换文件名中间的 .bmp。

As mentioned, this isn't going to change the format of a image file. To do that you would need to use a graphics library.

如前所述,这不会改变图像文件的格式。为此,您需要使用图形库。

回答by Sam Ingrassia

You can use this to rename the file http://us2.php.net/renameand this http://us2.php.net/manual/en/function.pathinfo.phpto get the basename of the file and other extension info..

您可以使用它来重命名文件http://us2.php.net/rename和这个http://us2.php.net/manual/en/function.pathinfo.php以获取文件的基本名称和其他扩展名信息..