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

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) {
    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>’;
    ?>