3

I've seen alot of functions which handle the retrival of an extension of a particular filename. I, myself, always use this solution of mine:

function extension( $filename = __FILE__ ) {
    $parts = explode('.', $filename);
    return (strtolower($parts[(sizeof($parts) - 1)]));
}

echo extension();              // php
echo extension('.htaccess');   // htaccess
echo extension('htaccess');    // htaccess
echo extension('index.php');   // php

Is that the best and the fastest approach?

  • 5
    pathinfo() http://www.php.net/manual/en/function.pathinfo.php with PATHINFO_EXTENSION – Mark Baker Mar 06 '13 at 21:41
  • possible duplicate of [How to extract a file extension in PHP?](http://stackoverflow.com/questions/173868/how-to-extract-a-file-extension-in-php) – John Conde Mar 06 '13 at 21:44

4 Answers4

4

I'll go ahead and say that it is not the best approach, and I suspect it isn't fastest either. The canonical way is using pathinfo.

$ext = pathinfo($file, PATHINFO_EXTENSION);

The problem with using explode is that you're creating an array, which necessarily takes up more memory (even if it is a trivial amount) which almost always leads to a decrease in speed. If you really want to go with a home-cooked non-canonical way, I suggest strrpos:

function get_extension($file)
{
    $pos = strrpos($file, '.');
    // for condition when strrpos returns FALSE on failure.
    if($pos !== FALSE) return substr($file, $pos);
    return FALSE;
}
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
2

Just use pathinfo()

$file =  pathinfo('index.php');
echo $file['extension']; // 'php'
Chris
  • 4,255
  • 7
  • 42
  • 83
1

That works, one thing i would change is your return:

return strtolower(end($parts));

I agree pathinfo is probably the better way I was just improving your code.

Pitchinnate
  • 7,517
  • 1
  • 20
  • 37
1
$file = "filename.php.jpg.exe";
echo substr($file, strrpos($file, "."));//.exe