Alex Rivera | Logout

Get extension from filename like variable

Asked 2011-06-12T07:45:28.890
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..

Edit
Report

1 Answer

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

answered 2011-06-12T07:49:44.923

Your Answer