所有方法本質歸納為兩類:
strrpos() + substr()explode() / pathinfo() + end()$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = (new SplFileInfo($filename))->getExtension();
$pos = strrpos($filename, '.');
$ext = $pos !== false ? substr($filename, $pos + 1) : '';
$ext = end(explode('.', $filename));
⚠ 若文件名無點,返回完整文件名;建議配合 strrpos 判斷。
$name = basename($filename);
$ext = ($pos = strrpos($name, '.')) !== false ? substr($name, $pos + 1) : '';
preg_match('/\.([^.]+)$/', $filename, $m);
$ext = $m[1] ?? '';
$ext = ltrim(strrchr($filename, '.'), '.');
| 方法 | 耗時(秒) | 相對性能 |
|---|---|---|
| pathinfo() | 0.42 | 基準 |
| SplFileInfo | 0.68 | 1.6x |
| strrpos+substr | 0.31 | 0.74x ⭐最快 |
| explode+end | 0.55 | 1.3x |
| basename+strrpos | 0.38 | 0.9x |
| preg_match | 1.85 | 4.4x |
| strrchr+ltrim | 0.45 | 1.07x |
| 輸入 | pathinfo | explode+end | strrpos+substr |
|---|---|---|---|
| file.txt | txt | txt | txt |
| .htaccess | htaccess | htaccess | htaccess |
| file.tar.gz | gz | gz | gz |
| file | '' | file ❌ | '' |
| path/to/file.txt | txt | txt | txt |
| file. | '' | '' | '' |
pathinfo($file, PATHINFO_EXTENSION) — 語義明確、邊界處理正確strrpos + substr — 性能最優,需自行處理無點情況SplFileInfo — 結合其他文件信息獲取時explode+end(誤判無擴展名文件)function getExtension($filename) {
$name = basename($filename);
$pos = strrpos($name, '.');
return $pos !== false ? substr($name, $pos + 1) : '';
}