21

Possible Duplicate:
How to extract a file extension in PHP?

I have a variable $filename="filename.ext" or $filename="filena.m.e.ext" or so on.. How can i extract the extension (here ext) from the variable / string? The variable may change or may have more than one dots.. In that case, i want to get the part after the last dot..

Community
  • 1
  • 1
Alfred
  • 21,058
  • 61
  • 167
  • 249

6 Answers6

58

see the answer :

$ext = pathinfo($filename, PATHINFO_EXTENSION);
Community
  • 1
  • 1
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • 1
    which is faster? ($imgname, strlen($imgname) - 4, 4); or pathinfo($filename, PATHINFO_EXTENSION); – zPuls3 Jun 13 '14 at 10:18
  • 2
    @zPuls3 `pathinfo($filename, PATHINFO_EXTENSION);` is way more exact because of different possible extension lengths. – Raisch Aug 06 '15 at 10:18
5

You can use the path info interrogation.

$info = pathinfo($file);

where

$info['extension']

contains the extension

BugFinder
  • 17,474
  • 4
  • 36
  • 51
4

you could define a function like this:

function get_file_extension($filename)
{
    /*
     * "." for extension should be available and not be the first character
     * so position should not be false or 0.
     */
    $lastDotPos = strrpos($fileName, '.');
    if ( !$lastDotPos ) return false;
    return substr($fileName, $lastDotPos+1);
}

or you could use the Spl_FileInfo object built into PHP

farzad
  • 8,775
  • 6
  • 32
  • 41
  • +1'ed for reminding of this. I always feel I don't use SPL as much as I could (and should). – Stephane Gosselin Jun 12 '11 at 07:56
  • +1 because this also work for URLs. – trante Mar 07 '14 at 22:08
  • well cool, but it's better to check from the end to the start! because the dot is almost in the end in general. with a loop, when we reach first dot, we substr ! Also is that faster better then pathinfo()? there is the fact that it return an array (different data) more computation to do! but what about pathinfo($img, PATHINFO_EXTENSION)?? does this compute all the data, or just execute a one info getting method – Mohamed Allal Nov 22 '17 at 17:01
3

You want to use a regular expression:

preg_match('/\.([^\.]+)$/', $filename);

You can test it out here to see if it gets you the result you want given your input.

kinakuta
  • 9,029
  • 1
  • 39
  • 48
2

There are many ways to do this, ie with explode() or with a preg_match and others.

But the way I do this is with pathinfo:

$path_info = pathinfo($filename);

echo $path_info['extension'], "\n";
Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65
0

You could explode the string using ., then take the last array item:

$filename = "file.m.e.ext";
$filenameitems = explode(".", $filename);

echo $filenameitems[count($filenameitems) - 1]; // .ext
// or echo $filenameitem[-1];
Scott Berrevoets
  • 16,921
  • 6
  • 59
  • 80