從 URL 字串解析檔案副檔名是常見需求(如判斷圖片類型、驗證上傳格式)。本文提供一個簡潔函數,並說明需注意的查詢字串、錨點等干擾因素。
<?php
/**
* 從 URL 取得副檔名(小寫)
*
* @param string $url
* @return string|null 副檔名,無則回傳 null
*/
function getUrlExtension(string $url): ?string {
// 1. 移除查詢字串與錨點
$path = parse_url($url, PHP_URL_PATH);
// 2. 取得路徑最後一段(檔名)
$filename = basename($path);
// 3. 解析副檔名
$ext = pathinfo($filename, PATHINFO_EXTENSION);
return $ext ?: null;
}
// 測試
$urls = [
'https://example.com/image.jpg',
'https://example.com/path/file.tar.gz',
'https://example.com/page?query=1',
'https://example.com/script.php#section',
'https://example.com/noext',
];
foreach ($urls as $url) {
echo "$url => " . (getUrlExtension($url) ?? '(無)') . "\n";
}
/*
輸出:
https://example.com/image.jpg => jpg
https://example.com/path/file.tar.gz => gz
https://example.com/page?query=1 => (無)
https://example.com/script.php#section => php
https://example.com/noext => (無)
*/
?>
| 函數 | 用途 |
|---|---|
| parse_url($url, PHP_URL_PATH) | 只取路徑部分,自動去除 query、fragment |
| basename($path) | 取得路徑最後一段(檔名) |
| pathinfo($file, PATHINFO_EXTENSION) | 標準函數取得副檔名,正確處理多點檔名(取最後一點後) |