32324 发表于 2014-5-8 10:16:41

php获取文件扩展名的几种方法

网上查阅后,自己动手写的:可能没有考虑周全存在错误。


//$filepath="d:\phptest\phptext.txt.zip";
    //$filepath="d:\phptest\phptext";
    //方法一
    function Extend_1($filename)
    {
      $extends=explode(".",$filename);
      $pos=count($extends)-1;//获取最后一个数组的位置
      $ext=end($extends);
      return $ext;
    //return $extends[$pos];
    }
    echo Extend_1($filepath);   //返回zip
    //方法二
    function Extend_2($filename)
    {
      $lastpos=strrchr($filename,".");//获取"."在filaname中的最后出现位置,并返回从该位置到最后的字符串
      return $lastpos;

    }
    echo Extend_2($filepath);//返回.zip
    //方法三
    function Extend_3($filename)
    {
      $lastpos=strripos($filename,"."); //获取"."在filaname中的最后出现位置
            $extend=substr($filename,$lastpos);
            return $extend;


    }
    echo Extend_3($filepath);//返回.zip
    //方法四
    function Extend_4($filename)
    {
      $strrev=strrev($filename); //反转字符串
      $firstindex=strpos($strrev,".");//获取"."在filaname中的第一次出现位置
            $extend=substr($strrev,0,$firstindex+1);
            return strrev($extend);

    }
    echo Extend_4($filepath); //返回.zip
    //方法五
    function Extend_5($filename)
    {
      $filainfo=pathinfo($filename);
      return $filainfo['extension'];
    }
//echo Extend_5($filepath);//返回zip
    //方法六
    function Extend_6($filename)   //注:最好使用这个
    {
      $filainfo=pathinfo($filename,PATHINFO_EXTENSION);
      return $filainfo;
    }
    echo Extend_6($filepath);//返回zip


页: [1]
查看完整版本: php获取文件扩展名的几种方法