PHP中获取文件扩展名

设定文件名为 $file = 'test.ex':

1、利用数组,将文件名转化为数组获取数组最后一个元素:

function get_extension($file)
{
  return end(explode('.', $file));
}

2、利用系统函数pathinfo:

2.1:

function get_extension($file)
{
    $info = pathinfo($file);
    return $info['extension'];
}

:2.2:

function get_extension($file)
{
    return pathinfo($file, PATHINFO_EXTENSION);
}

3、利用点字符'.'的最后出现位置:

function get_extension($file)
{
    return substr($file, strrpos($file, '.')+1); //strrpos返回最后一次出现的索引位置

  //或者:return substr(strrchr($file, '.'), 1);
  //strrchr($file, '.')返回最后出现点字符的地方到结束的部分(包括点字符,所以需要再次substr) 
}

思考:

当文件名为 1、$file = 'test' (无后缀)  2、$file = 'test.dir/test'(最后一次出现点字符的位置后的字符并不是后缀)

运行测试脚本表明:2.2适用于任何情况

猜你喜欢

转载自www.cnblogs.com/jongty/p/11688792.html