How can I change a file's extension using PHP?

前端 未结 11 2071
清歌不尽
清歌不尽 2020-12-10 00:43

How can I change a file\'s extension using PHP?

Ex: photo.jpg to photo.exe

相关标签:
11条回答
  • 2020-12-10 01:21

    For regex fans, modified version of Thanh Trung's 'preg_replace' solution that will always contain the new extension (so that if you write a file conversion program, you won't accidentally overwrite the source file with the result) would be:

    preg_replace('/\.[^.]+$/', '.', $file) . $extension
    
    0 讨论(0)
  • 2020-12-10 01:22

    You could use basename():

    $oldname = 'path/photo.jpg';
    $newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR  : '') . basename($oldname, 'jpg') . 'exe';
    

    Or for all extensions:

    $newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR  : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';
    

    Finally use rename():

    rename($oldname, $newname);
    
    0 讨论(0)
  • 2020-12-10 01:28

    Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:

    function replace_extension($filename, $new_extension) {
        return preg_replace('/\..+$/', '.' . $new_extension, $filename);
    }
    

    Then use the rename() function to rename the file with the new filename.

    0 讨论(0)
  • 2020-12-10 01:30

    I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:

    // 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);
      }
    }
    

    This worked for my purposes.

    0 讨论(0)
  • 2020-12-10 01:32
    substr_replace($file , 'png', strrpos($file , '.') +1)
    

    Will change any extension to what you want. Replace png with what ever your desired extension would be.

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