PHP Functions to Get and Remove the File Extension from a String

I use these regular expressions all the time, but it's much more convenient to have them both in convenient PHP functions.

// Returns only the file extension (without the period).
function file_ext($filename) {
return preg_match('/\./', $filename) ? preg_replace('/^.*\./', '', $filename) : ''; } // Returns the file name, less the extension. function file_ext_strip($filename){ return preg_replace('/.[^.]*$/', '', $filename); }

You can also use the built-in pathinfo function to achieve the same result:

$filename = '/path/to/file.ext';

echo pathinfo($filename)['extension']; // "ext"
echo pathinfo($filename)['filename']; // "file"
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.