Get file extension on PHP

There are many ways to retrieve files extension with PHP, but we will have to choose one that feets our needs and gives more reliable results.
When dealing with file extension you should know that a file extension is not always 3 characters long (ex:  foto.jpeg, index.html) and that it doesn’t start after the last dot (.) in the file name (ex: program.tar.gz, config.php.inc).

Let’s write the filename_details function that we will use to retrieve the extension of the file module.tar.bz or any file you have:

<?php
function filename_details($filename, $dots){
  $filename_no_ext = $filename;
  while($dots--){
    $temp_arr = explode('.', $filename_no_ext);
    $extension = '.'.array_pop($temp_arr).$extension;
    $filename_no_ext = implode('.', $temp_arr);
  }
  $extension = substr($extension, 1);
  return array($filename_no_ext, $extension);
}
print_r(filename_details('module.tar.bz',2));
 
/*
Output: 
Array
(
  [0] => module
  [1] => tar.bz
)
//*/
 
?>

Related links

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">