How to get(extract) a file extension in PHP?
This is a question you can read everywhere on the web with various answers :
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*.([^.]+)$/D', '$1', $filename);
$exts = split("[/.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
etc.
However, there is always "the best way" and it should be on Stack Overflow.
People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet pathinfo()
:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This is fast and built-in. pathinfo()
can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. EG:
setlocale(LC_ALL,'en_US.UTF-8');
Also note this doesn't take in consideration the file content or mimetype, you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL ressources path, which are covered using PARSE_URL.
Enjoy
pathinfo()
An example...
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
use safer: PARSE_URL
(instead of PATHINFO
)
for example, url is http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ
PATHINFO returns:
$x = pathinfo($url);
$x['dirname']
链接地址: http://www.djcxy.com/p/8220.html
上一篇:
在Python中从文件名中提取扩展名
下一篇:
如何在PHP中获取(提取)文件扩展名?