在PHP中獲取副檔名方法

2021-09-01 14:53:30 字數 1297 閱讀 5111

在php中獲取副檔名方法有很多,常用的大致有以下幾種,收藏備用!

第1種方法:

function get_extension($file)

第2種方法:

function get_extension($file)

第3種方法:

function get_extension($file)

第4種方法:

function get_extension($file)

第5種方法:

function get_extension($file)

以上幾種方式粗看了一下,好像都行,特別是1、2種方法.但是仔細考慮一下,前四種方法都有各種各樣的毛病.要想完全正確獲取檔案的副檔名,必須要能處理以下三種特殊情況.

沒有副檔名

路徑中包含了字元.,如/home/test.d/test.txt

路徑中包含了字元.,但檔案沒有副檔名.如/home/test.d/test

很明顯:

1、2不能處理第三種情況.

3不能正確處理第一三種情況.

4可以正確處理,但是在不存在副檔名時,會發出乙個警告.

只有第5種方法才是最正確的方法.

順便看一下pathinfo方法.官網上介紹如下:

它會返回乙個陣列,包含最多四個元素,但是並不會一直有四個,比如在沒有副檔名的情況下,就不會有extension元素存在,所以第4種方法才會發現警告.但是phpinfo還支援第二個引數.可以傳遞乙個常量,指定返回某一部分的資料:

pathinfo_dirname - 目錄

pathinfo_basename - 檔名(含副檔名)

pathinfo_extension - 副檔名

pathinfo_filename - 檔名(不含副檔名,php>5.2)

php獲取副檔名

第一種 123 4567 891011 1213 1415 獲取副檔名 substr strrchr name.txt 1 function fileextension fstr file extension fileextension abc def.g 123 print r file exte...

PHP獲取副檔名

第一種 tok strtok string,使用strtok將字串分割成乙個個令牌 while tok count count arr i count 1 file type arr i 第二種 arr explode string 使用explode 函式分割字串,返回值是乙個陣列 count c...

php獲取 副檔名

1 str as.da.efg 2 獲取檔案字尾名 3 strrchr 查詢指定字元在字串中的最後一次出現 4echo substr strrchr str,1 5 67 strrpos 計算指定字串在目標字串中最後一次出現的位置 8echo substr str,strrpos str,1 9 1...