Skip to content

Instantly share code, notes, and snippets.

@evgv
Created September 23, 2016 08:28
Show Gist options
  • Save evgv/3057d9b3bd829f7a416d010d70b252ff to your computer and use it in GitHub Desktop.
Save evgv/3057d9b3bd829f7a416d010d70b252ff to your computer and use it in GitHub Desktop.
PHP. Detects the file extension from a given string.

#Get File Extension

Detects the file extension from a given string. This function returns the text following the last dot of the file name, so more complicated file extensions such as .tar.gz are only returned as ".gz".

function file_ext($file) {
  $last_dot = strrpos($file, '.');
  if ($last_dot !== false) {
    return strtolower(substr($file, $last_dot + 1));
  }
  return 'file';
}

Examples:

echo file_ext('test.txt'); // "txt"
echo file_ext('PAGE.HTML'); // "html"
echo file_ext('config'); // "file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment