Getting File's Extension with Regular Expression
Jun 18, 2008
Getting file extension is not as easy as it looks. This is because there is no strict format for file extensions. Consider the following file names:
test.jpg
another image.jpeg
PHP Tutorial from Nashruddin.pdf
unusual.name.for.a.file.extension
my favorite, music.mp3
You cannot get the extension with substr($filename, -n), for example.To obtain the extension from filenames above, you have to use regular expression. See the following example.
<?php $filenames = array( 'test.jpg', 'longfilename.html', 'PHP Tutorial from Nashruddin.pdf', 'unusual.name.for.a.file.extension', 'another, weird, file.jpeg', 'my favorite song.mp3' ); foreach ($filenames as $filename) { preg_match("/\.([^\.]+)$/", $filename, $matches); print $matches[1] . '<br>'; } /* will print: jpg html pdf extension jpeg mp3 */ ?>
Keywords: regular expression, preg_match, file extension, php
Share:
Save to del.icio.us
Digg this!

Add your comment
Thanks - works a treat