Get file extension in PHP
Using pathinfo()
(PHP 4 >= 4.0.3, PHP 5)
$fileName = '/home/documents/my.file.doc'; $fileInfo = pathinfo($fileName); $fileExtension = $fileInfo['extension'];
echo $fileExtension; will output: doc
As you can see fileinfo() offers more information about the file and it works only for the file name (my.file.doc) or for the whole path (/home/documents/my.file.doc):
print_r($fileInfo);
will output:
Array
(
[dirname] => /home/documents
[basename] => my.file.doc
[extension] => doc
[filename] => my.file
)
Using substr() and strpos()
$path = '/home/documents/my.file.doc'; $fileName = substr($path, strrpos($path, '/') + 1); $fileExtension = substr($fileName, strrpos($fileName, '.') + 1);
echo $fileExtension; will output: doc
Notice: it will give erroneous results if the file does not have an extension (also for linux hidden files starting with a dot)
Using preg_match()
Avoid preg_match() in favor of strpos() if possible because it is faster.
Get directory and file name
$path = '/home/documents/my.file.doc';
preg_match('|^(.*)([^/]+)$|U', $path, $matches);
U modifier = non greedy, see http://php.net/manual/en/reference.pcre.pattern.modifiers.php
print_r($matches);
will output:
Array
(
[0] => /home/documents/my.file.doc
[1] => /home/documents/
[2] => my.file.doc
)
Get file extension
$path = '/home/documents/my.file.doc';
preg_match('|([^\.]+)$|', $path, $matches);
$fileExtension = $matches[1];Latest news
- - S5 Slide Show System: PowerPoint on Linux
- - µTorrent for Linux
- - Linux audio tagger
- - Gnome 3 release date - interview with Stormy Peters
- - Ubuntu Maverick Meerkat Beta Released
- - Ubuntu Maverick Meerkat frozen
- - Tab Candy for Firefox
- - Ubuntu font launched for beta testing
- - Interview with Richard Stallman
- - Linux Mint 9 KDE released
- - Gnome 3 release date delayed to march 2011
Comentarii
Prasenjit (16.12.2010)
Best solution to get only extension of a file