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

前端 未结 11 2070
清歌不尽
清歌不尽 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:07

    Better way:

    substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension
    

    Changes made only on extension part. Leaves other info unchanged.

    It's safe.

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

    Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:

    • answer by Tony Maro (pathinfo) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.
    • answer by Matt (substr_replace) took 0.000010013580322266 seconds.
    • answer by Jeremy Ruten (preg_replace) took 0.00070095062255859 seconds.

    Therefore, I would suggest substr_replace, since it's simpler and faster than others.

    Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn't beat substr_replace:

    $parts = explode('.', $inpath);
    $parts[count( $parts ) - 1] = 'exe';
    $outpath = implode('.', $parts);
    
    0 讨论(0)
  • 2020-12-10 01:11

    http://www.php.net/rename

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

    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)
  • 2020-12-10 01:17

    Replace extension, keep path information

    function replace_extension($filename, $new_extension) {
        $info = pathinfo($filename);
        return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '') 
            . $info['filename'] 
            . '.' 
            . $new_extension;
    }
    
    0 讨论(0)
  • 2020-12-10 01:21

    In modern operating systems, filenames very well might contain periods long before the file extension, for instance:

    my.file.name.jpg
    

    PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:

    function replace_extension($filename, $new_extension) {
        $info = pathinfo($filename);
        return $info['filename'] . '.' . $new_extension;
    }
    
    0 讨论(0)
提交回复
热议问题