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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章