You're here: Home / PHP /

Getting File's Extension with Regular Expression

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:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifComments

Thanks - works a treat

comment.gifAdd your comment

(required, will not be published) (optional)