开发者

Get extension from filename like variable [duplicate]

This question already has answers here: Closed 10 years ago.

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开发者_StackOverflow 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..


see the answer :

$ext = pathinfo($filename, PATHINFO_EXTENSION);


You can use the path info interrogation.

$info = pathinfo($file);

where

$info['extension']

contains the extension


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


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.


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";


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜