Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP获取文件扩展名的最短方法_Php_File Extension - Fatal编程技术网

使用PHP获取文件扩展名的最短方法

使用PHP获取文件扩展名的最短方法,php,file-extension,Php,File Extension,我见过很多函数,它们处理特定文件名扩展名的检索。一、 我自己,始终使用我的解决方案: function extension( $filename = __FILE__ ) { $parts = explode('.', $filename); return (strtolower($parts[(sizeof($parts) - 1)])); } echo extension(); // php echo extension('.htaccess');

我见过很多函数,它们处理特定文件名扩展名的检索。一、 我自己,始终使用我的解决方案:

function extension( $filename = __FILE__ ) {
    $parts = explode('.', $filename);
    return (strtolower($parts[(sizeof($parts) - 1)]));
}

echo extension();              // php
echo extension('.htaccess');   // htaccess
echo extension('htaccess');    // htaccess
echo extension('index.php');   // php

这是最好和最快的方法吗?

我会继续说,这不是最好的方法,我怀疑它也不是最快的方法。规范的方法是使用

使用
explode
的问题是,您正在创建一个数组,这必然会占用更多内存(即使是很小的内存),这几乎总是会导致速度降低。如果你真的想用一种家常的非正统方式,我建议:


行得通,我想改变的一件事是你的回报:

return strtolower(end($parts));
我同意pathinfo可能是我改进代码的更好方法。

只需使用


pathinfo()和pathinfo_扩展可能重复是的,你说得对!谢谢,您的解决方案很有帮助!:)<代码>substr($file,strrpos($file,“.”+1)用于删除dot不是我的功能更简单一点…:)为了你,为了你的努力
function get_extension($file)
{
    $pos = strrpos($file, '.');
    // for condition when strrpos returns FALSE on failure.
    if($pos !== FALSE) return substr($file, $pos);
    return FALSE;
}
return strtolower(end($parts));
$file =  pathinfo('index.php');
echo $file['extension']; // 'php'
$file = "filename.php.jpg.exe";
echo substr($file, strrpos($file, "."));//.exe