Change file extension

前端 未结 5 1524
遇见更好的自我
遇见更好的自我 2021-01-12 06:46

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

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

相关标签:
5条回答
  • 2021-01-12 07:20

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

    $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.

    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.

    0 讨论(0)
  • 2021-01-12 07:21

    rename() the file, substituting the new extension.

    0 讨论(0)
  • 2021-01-12 07:34

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

    0 讨论(0)
  • 2021-01-12 07:36

    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:

    $filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
    
    0 讨论(0)
  • 2021-01-12 07:37
    $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 :)

    0 讨论(0)
提交回复
热议问题