php 从文件名中获取扩展名,如变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6320804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get extension from filename like variable
提问by blasteralfred Ψ
Possible Duplicate:
How to extract a file extension in PHP?
可能的重复:
如何在 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..
我有一个变量$filename="filename.ext"
或$filename="filena.m.e.ext"
诸如此类。我如何ext
从变量/字符串中提取扩展名(此处)?变量可能会改变或可能有多个点.. 在这种情况下,我想得到最后一个点之后的部分..
回答by farzad
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_FileInfoobject built into PHP
或者你可以使用PHP 内置的Spl_FileInfo对象
回答by BugFinder
You can use the path info interrogation.
您可以使用路径信息询问。
$info = pathinfo($file);
where
在哪里
$info['extension']
contains the extension
包含扩展名
回答by kinakuta
回答by stefgosselin
There are many ways to do this, ie with explode() or with a preg_match and others.
有很多方法可以做到这一点,即使用explode() 或使用preg_match 等。
But the way I do this is with pathinfo:
但我这样做的方式是使用 pathinfo:
$path_info = pathinfo($filename);
echo $path_info['extension'], "\n";
回答by Scott Berrevoets
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];