1. 程式人生 > >PHP獲取檔案字尾名(提供7種方法) 阿星小棧

PHP獲取檔案字尾名(提供7種方法) 阿星小棧

1.$file = 'x.y.z.png';
echo substr(strrchr($file, '.'), 1);
解析:strrchr($file, '.')   
 strrchr() 函式查詢字串在另一個字串中最後一次出現的位置,並返回從該位置到字串結尾的所有字元
2.$file = 'x.y.z.png';
echo substr($file, strrpos($file, '.')+1);
解析:strrpos($file, '.')   
查詢 "." 在字串中最後一次出現的位置,返回位置   substr()從該位置開始擷取
3.$file = 'x.y.z.png';
$arr=explode('.', $file);
echo $arr[count($arr)-1];
4.$file = 'x.y.z.png';
$arr=explode('.', $file);
echo end($arr);  //end()返回陣列的最後一個元素
5.$file = 'x.y.z.png';
echo strrev(explode('.', strrev($file))[0]);
6.$file = 'x.y.z.png';
echo pathinfo($file)['extension'];
解析:pathinfo() 函式以陣列的形式返回檔案路徑的資訊。包括以下的陣列元素:
[dirname]
[basename]
[extension]
7.$file = 'x.y.z.png';
echo pathinfo($file, PATHINFO_EXTENSION);
總結:字串擷取2種,陣列分割3種,路徑函式2種

援引:https://blog.csdn.net/zls986992484/article/details/52629684