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

March 11, 2009

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) {
	if( !preg_match('/\./', $filename) ) return '';
	return preg_replace('/^.*\./', '', $filename);
}

// Returns the file name, less the extension.
function file_ext_strip($filename){
    return preg_replace('/\.[^.]*$/', '', $filename);
}

Discussion

  1. Very handy, and much more elegant than the ‘traditional’ explode() / strstr() / substr() etc. methods.

    June 19th, 2009Rob C
  2. Nice one. I just started working with Regex in PHP and this has definitely come in very handy.

    November 1st, 2012Helen Neely