How to remove file extension in PHP

3 Answers

0 votes
function removeExtension($filename) {
    return pathinfo($filename, PATHINFO_FILENAME);
}

echo removeExtension('test.php') . "\n"; 
echo removeExtension('example.a.b.jpg') . "\n"; 

 

/*
run:

test
example.a.b

*/

 



answered Jun 12, 2024 by avibootz
edited Oct 11 by avibootz
0 votes
function removeExtension($filename) {
    return substr($filename, 0, strrpos($filename, '.'));
}

echo removeExtension('test.php') . "\n"; 
echo removeExtension('example.a.b.jpg') . "\n"; 

 

/*
run:

test
example.a.b

*/

 



answered Jun 12, 2024 by avibootz
edited Oct 11 by avibootz
0 votes
/**
 * Removes the file extension from a filename.
 *
 * Examples:
 *   document.pdf      -> document
 *   archive.tar.gz    -> archive.tar
 *   image.jpg         -> image
 *   README            -> README
 *
 * @param string $filename The filename or path.
 * @return string The filename without its final extension.
 */
function removeFileExtension(string $filename): string
{
    $directory = pathinfo($filename, PATHINFO_DIRNAME);
    $basename  = pathinfo($filename, PATHINFO_FILENAME);

    // If the input contains a directory path,
    // reconstruct the path without the extension.
    if ($directory !== '.') {
        return $directory . DIRECTORY_SEPARATOR . $basename;
    }

    return $basename;
}

// Example usage
echo removeFileExtension('document.pdf') . PHP_EOL;       // document
echo removeFileExtension('archive.tar.gz') . PHP_EOL;     // archive.tar
echo removeFileExtension('images/photo.jpg') . PHP_EOL;   // images/photo
echo removeFileExtension('README') . PHP_EOL;             // README


/*
run:

document
archive.tar
images/photo
README

*/

 



answered Oct 11 by avibootz
...