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

/ Published in: PHP
Save to your folder(s)

A flexible way to get the file name without the extension

Copy this code and paste it in your HTML
  1. /*
  2. Detailed notes are below the code.
  3. */
  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 );
  13. echo 'The extension is '.$str_extension;
  14. echo '<br /> The file name (without the extension) is: '.$filename_without_extension;
  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:
  20. 1. filename_small.jpg
  21. 2. filename_medium.jpg
  22. 3. filename_large.jpg
  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.
  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


RSS Icon Subscribe to comments

You need to login to post a comment.