/**
* 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
*/