Skip to content
Related Articles

Related Articles

How to extract extension from a filename using PHP?
  • Difficulty Level : Expert
  • Last Updated : 08 Mar, 2021

There are a few different ways to extract the extension from a filename with PHP. They are:

  1. Using pathinfo(): The pathinfo() is a function that returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned. If the second parameter is true, it will return specific data.

    PHP




    <?php
    $file_name = 'gfg.html';
    $extension = pathinfo($file_name, PATHINFO_EXTENSION);
    echo $extension;
    ?>
    Output
    html
  2. Explode the file variable and get the last array element to be the file extension. The PHP end() function is used to get the last element of the array.

    PHP




    <?php
    $file_name = 'gfg.html';
    $temp= explode('.',$file_name);
    $extension = end($temp);
    echo $extension;
    ?>
    Output



    html
  3. Using substr() and strrchr() functions:

    substr(): A part of the string is returned.

    strrchr(): The last occurrence of a string inside another string is determined.

    PHP




    <?php
    $file_name = 'gfg.html';
    $extension = substr(strrchr($file_name, '.'), 1);
    echo $extension;
    ?>
    Output
    html
  4. Using strrpos() to find the last occurrence position of a ‘.’ in a filename and enhance the file position by 1 to explode string (.)

    PHP




    <?php
    $file_name = 'gfg.html';
    $extension = substr($file_name, strrpos($file_name, '.') + 1);
    echo $extension;
    ?>
    Output
    html
  5. Using regular expressions like replace and search. The first parameter of the preg_replace() function is the search pattern, the second parameter $1 is a reference to whatever matches the first (.*), and the third parameter is the file name.

    PHP




    <?php
    $file_name = 'gfg.html';
    $extension = preg_replace('/^.*\.([^.]+)$/D', '$1', $file_name);
    echo $extension;
    ?>
    Output
    html
My Personal Notes arrow_drop_up
Recommended Articles
Page :