Posted By

donkeykong on 04/03/11


Tagged

file name filename extension


Versions (?)

Get the file name without the extension from a file's full name


 / Published in: PHP
 

A flexible way to get the file name without the extension

  1. /*
  2. Detailed notes are below the code.
  3. */
  4.  
  5. $str_full_filename = 'tricky_filename_.js.jpg.version2.jpg';
  6. $arr = explode( '.',$str_full_filename );
  7. $int_last_element = sizeof( $arr )-1;// the last element contains the extension
  8. $str_extension = $arr[ $int_last_element ];
  9. array_pop( $arr );// the filename (without the extension), doesn't need the last element
  10. $filename_without_extension = implode( '.',$arr );
  11.  
  12.  
  13. echo 'The extension is '.$str_extension;
  14. echo '<br /> The file name (without the extension) is: '.$filename_without_extension;
  15.  
  16.  
  17. /*
  18. This is a group of methods to get the extension of a file or get a filename without the extension; this is especially useful when you need to copy an image (say filename.jpg), resize and rename to something like the following:
  19.  
  20. 1. filename_small.jpg
  21. 2. filename_medium.jpg
  22. 3. filename_large.jpg
  23.  
  24. I'm not covering how to resize images, just a way to copy the name and the extension so you can keep names consistent.
  25.  
  26. The way I did this is to anticipate strange file names, so files with an extension name in it more than once won't cause errors or inconsistency.
  27. */

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: mstksg on March 21, 2013

alternatively, if you know what the extension is beforehand

basename(filename,extension)

http://php.net/manual/en/function.basename.php

echo basename("filename_small.jpg",".jpg");
// => "filename_small"

You need to login to post a comment.