PHP Functions to Get and Remove the File Extension from a String

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

I use these regular expressions all the time, but it’s much more convenient to have them both in convenient PHP functions.

file_ext()

Returns only the file extension (without the period).

function file_ext($filename) {
	if( !preg_match('/\./', $filename) ) return '';
	return preg_replace('/^.*\./', '', $filename);
}

file_ext_strip()

Returns the file name, less the extension.

function file_ext_strip($filename){
    return preg_replace('/\.[^.]*$/', '', $filename);
}
If you enjoyed this article, please share it with a friend!

4 Responses to PHP Functions to Get and Remove the File Extension from a String

  1. Igor Escobar says:

    I test it using the regex pal and the result of the first function does’t work so well.

    http://regexpal.com/?flags=&regex=(^.*.)&input=igor.escobar.jpg

  2. Cory LaViska says:

    @Igor Escobar: Sorry! You were right, there was an escape issue so the backslashes weren’t appearing in the regex pattern. They work now :)

  3. Rob C says:

    Very handy, and much more elegant than the ‘traditional’ explode() / strstr() / substr() etc. methods.

  4. Bill Brown says:

    Of course, you could also just use PHP’s built-in functions for this:

    <?php
    function file_ext ($name)
    {
    $info = pathinfo($name);
    return $info['extension'];
    }
    function file_ext_strip ($name)
    {
    $info = pathinfo($name);
    return $info['filename'];
    }

    # DEMO
    $filename = "/path/to/some.file";
    echo file_ext($filename).’<br>’;
    echo file_ext_strip($filename).’<br>’;
    ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>