取得副檔名看似簡單,實則有「無副檔名」、「路徑含點」、「隱藏檔」等邊界情況。本文比較五種常見寫法,指出唯有 pathinfo() 搭配 PATHINFO_EXTENSION 為最穩健解法。
// 1. substr + strrchr
substr(strrchr($file, '.'), 1);
// 2. substr + strrpos
substr($file, strrpos($file, '.') + 1);
// 3. explode + end
end(explode('.', $file));
// 4. pathinfo 陣列取值
$info = pathinfo($file);
$info['extension'] ?? ''; // 無副檔名會觸發 Notice
// 5. pathinfo 指定常數(推薦)
pathinfo($file, PATHINFO_EXTENSION); // 無副檔名回傳空字串,不報錯
| 輸入 | 方法 1-3 | 方法 4 | 方法 5 |
|---|---|---|---|
| test.jpg | jpg | jpg | jpg |
| test | test (錯) | Notice | '' (正確) |
| /path.with.dots/test | test (錯) | Notice | '' (正確) |
| /path.with.dots/test.txt | txt | txt | txt |
| .htaccess | htaccess | htaccess | htaccess |
$file = '/www/htdocs/image.jpg';
print_r(pathinfo($file));
/*
Array(
[dirname] => /www/htdocs
[basename] => image.jpg
[extension] => jpg
[filename] => image // PHP 5.2+
)
*/
PATHINFO_DIRNAME = 1PATHINFO_BASENAME = 2PATHINFO_EXTENSION = 4PATHINFO_FILENAME = 8 (PHP 5.2+)注意:常數不可用位元或運算組合,若需多欄位請用陣列版 pathinfo($file)。
請直接使用 pathinfo($filename, PATHINFO_EXTENSION),它能正確處理所有邊界情況,且無額外錯誤訊息,是 PHP 官方推薦的標準做法。