0

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

I found the following function to get the extension of a file in a tutorial, but I think it's a bit too long. So I thought there would be a way to shorten this.

function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) return "";
    $l = strlen($str) - $i;
    $ext = substr($str, $i+1, $l);
    return $ext;
}

The $str would be a filename.
Is there a way to shorten this function, without affecting stability and output?
I've done something like this:

function getExtension($str) {    
    $ext = pathinfo($str)['extension'];
    return $ext;
}

But that didn't work for me, but probably I did something wrong.

Community
  • 1
  • 1
  • 3
    You could start with indenting it. :) I have a feeling this question is better suited to codereview.stackexchange.com – GordonM Oct 17 '12 at 09:16
  • I wished that would make a difference ;) Didn't know that codereview.stackexchange.com even existed. Good thing that that exists! Thanks for notifying! – Bastiaan ten Klooster Oct 17 '12 at 09:19
  • Take a look at [How to extract a file extension in PHP?](http://stackoverflow.com/questions/173868/how-to-extract-a-file-extension-in-php?rq=1) – Florent Oct 17 '12 at 09:19
  • on your second example, it should be `pathinfo($str,...` instead of `pathinfo($_FILES['image']['name']....` – pleasedontbelong Oct 17 '12 at 09:19

3 Answers3

6

The correct way would be the use the pathinfo() function.

$extension = pathinfo($filename, PATHINFO_EXTENSION);
Dennis Haarbrink
  • 3,738
  • 1
  • 27
  • 54
2

Moved to: https://stackoverflow.com/a/12932338/367456 - This answer will be deleted.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    Might be worth mentioning that the `$ext = (new SplFileInfo($path))->getExtension();` syntax only works in PHP>=5.4 – Dennis Haarbrink Oct 17 '12 at 09:42
  • @DennisHaarbrink: Yes that type of de-referencing is only available in PHP >= 5.4, the SplFileInfo itself is available in PHP 5 >= 5.1.2. – hakre Oct 17 '12 at 09:44
0

Maybe something along the lines of:

function getExtension($filename)
{
    $parts = explode('.', $filename);

    if (sizeof($parts) > 1) {
        return array_pop($parts);
    }

    return '';
}
smottt
  • 3,272
  • 11
  • 37
  • 44