How to get a file extension
How to get a file extension in PHP:
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
How to get a file extension in Perl:
my $ext = ($file_name =~ m/([^.]+)$/)[0];
How to get a file extension in Ruby:
ext = File.extname(file_name)
How to get a file extension in Bash:
ext=${file_name##*.}
name=${file_name%.*}
How to get a file extension in Python (thanks to Jensen):
import os ext = os.path.splitext(file_name)[1]
—
Got more? Please post a comment.
31 May 2008 Arnold Daniels




It would be interesting to provide code with the following two examples:
foo.tgz
foo.tar.gz
This would essentially require two snippets for each language… depending on what the user wanted to do.
Python:
import os
ext = os.path.splitext(file_name)[1]
If “file_name” is “my.file.txt” the “ext” variable will contain “.txt”.
For .tar.gz, only gz is seen as the extension. If necessary, you need to make an exception for tar.gz.
Also you might want to say that this it should only give an extension when the filename has a dot, eg README has no extension. This isn’t done correctly with the Perl and bash example.
With a regex it would be
Javascript:-
/[^.]{1,3}$/.exec(’.testest.jpg’)
Windows commandline:
echo %~x1
@Gareth Heyes:
extension is usually defined as last part after a dot (not limited to three characters). So it would be
/[^.]+$/.exec(’filename.with.extension’) // here extension is ‘extension’
@Arnold:
Your comment form does not work with javascript off.
C# –
FileInfo f = new FileInfo(”test.txt”);
string ext = f.Extension; # ext = txt
D
char[] ext =std.path.getExt(fnam)
gtkds (javascript)
var ext= Path.getExt(fname)
// what about writing classes/functions for common operations?
$ext = File::ext($filename);
// included file
class File {
static function ext($filename)
{
return pathinfo($file_name, PATHINFO_EXTENSION);
}
}
Hi Arnold, sorry if I’m posting here, but I did not found another way to contact you.
I’ve just read a message that you posted on the forum of the mysql website.
You wrote that you’ve got a php lib based on fast regexp that can parse a mysql query string to retrieve information like: operation (INSERT, UPDATE..), tables, fields… and so on.
I was looking for such a library, can you help me, please?
Thank you in advance!
in C# (alternative):
string path = “C:\file.txt”;
string ext = path.SubString(path.LastIndexOf(”.”) + 1);
@ ace for his ‘making it a class’ business, in a proper OO thingy, you’d more likely see a structure like
$file = new File(’somefile.txt’);
echo $file->GetExtension();
since ‘putting it into a class’, as described by you, is basically just ‘wrapping the php function into another function, with the additional overhead of putting it into a class in order to simulate namespaces’.
private credit record score in calgary alberta…
redouble?missed,leafed!hatred,…
my ($ext) = $file_name =~ m/([^.]+$)/;
In a CGI with perl, I got the extension with:
my $ext = ($file_name =~ m/.*\.(.+)$/)[0];
Thanks for ur kind help.
PHP
Keep it simple!
Use explode!
$extension = end(explode(’.', $file));
Returns everything after the last “.”.
Using explode won’t give you the wanted result:
$file = “/etc/passwd”;
$extension = end(explode(’.’, $file));
echo $extension; // Outputs ‘/etc/passwd’
For PHP use pathinfo() as described in the above article.
end(explode works quite well as posted. Without the “end” you will get the undesired result mentioned above.
Here is some info on explode and also has an example of the end(explode method that shows that it does work quite well.
http://us3.php.net/manual/en/function.explode.php#87049
My expertise quite limited. Been writing in php off and on only about 5 years now. The explode method works for me though in many ways.
The goal was to return the extension of a file name. Just like the examples at the top of the page here. Right?
That explode example will do just that. I use it all the time in my snippets. Efficiency is relative to the end app I guess though.
$file = “someimage.jpg”; //or even some.image.jpg
$extension = end(explode(’.', $file));
outputs jpg
// It does everything after the last ‘.’
I was told by many it is the most efficient way to grab a file name extension with php. If there is a way that uses less resources, I will use it instead.
Using pathinfo:
$path_parts = pathinfo(’/www/index.html’);
Enables me to:
echo $path_parts['dirname'], “\n”;
echo $path_parts['basename'], “\n”;
echo $path_parts['extension'], “\n”;
echo $path_parts['filename'], “\n”;
I “think” pathinfo uses more “resources” than just getting the specific result as I did in the explode example. I could be very wrong. If someone could prove one is method “better” that the other, I will use the better one for sure! I also become concerned about security. The explode method exposes more by far. But it is php.
Now, in cases where you need to break a file name up, do some pattern matching or directory creation then reconstruct it all later for some reason or another, pathinfo has everything you need all ready and waiting. I use it for that frequently. But, when I don’t, I use the explode method to grab parts of a string or file. When I actually write apps in php that is..
Great topic. So many ways to perform a seemingly simple task. But, just because it is simple does not mean it is easy!
Thanks guys!
Sandor: Thanks for you input, but please have a closer look at my comment.
Using explode will not work correctly if the file does not have an extension. It will work for ‘/var/www/someimage.jpg’, but not for ‘/etc/group’. Please execute the code and see for your self.
Please also note the PATHINFO_% constants. You don’t need to get the whole array and than get the extension part from that.
This is most definitely faster than doing an explode + end, since you don’t need to create an array, which is a relative expensive operation.
I made a error in the benchmark code. Updated the profiling results
Excellent, thank you… Your input here forces me to test all my snippets in Zend studio. What’s the use of having it if I don’t use it!
As far as the security holes when no extension is present (and other possibilities), I was sanitizing before I got to explode. Chalking up some more time on to the explode method.
Thanks again!
So in PERL, would using
$string= do some /stuff $ENV(’PATH_INFO’)/g;
be a better/safer way to grab an extension or even a whole ?query. Replacing the need for a query and even avoiding loading a perl module like CGI. Hence more security and a so on like:
#!/usr/bin/perl -Tw
use strict;
use warnings;
BEGIN{$SIG{__DIE__} = \&FatalErr} #my dies go to a sub#
$ENV{PATH} = “bin:/usr/bin”;
delete ($ENV{qw(IFS CDPATH BASH_ENV ENV)});
my $string=”";
$string= do some /stuff with $ENV(’PATH_INFO’) /here/;
#sanitize $string here
#split it up as needed..
All vars are now ready…
Prob a one liner that can break up the whole deal after taint.
That was just a quick type so, don’t take it literally, just a concept.
I have a PERL sub I am working on that I would like to share here for help in developing it. Everyone who serves up images could use it when done. I will find the proper category to post it here when I clean it up a bit..
For Perl, you forgot the parens around your match group:
my $ext = ($file_name =~ m/([^.]+)$/)[0];
Thanks! This helped a lot!!
CommonJS:
From http://wiki.commonjs.org/wiki/Filesystem/A, works on Narwhal:
require(”file”).extension(fileName);