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

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

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.


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

Tags:

Php

File