How do I get a file extension in PHP?

前端 未结 28 2236
一向
一向 2020-11-21 22:45

This is a question you can read everywhere on the web with various answers:

$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1         


        
相关标签:
28条回答
  • 2020-11-21 23:09

    A quick fix would be something like this.

    // Exploding the file based on the . operator
    $file_ext = explode('.', $filename);
    
    // Count taken (if more than one . exist; files like abc.fff.2013.pdf
    $file_ext_count = count($file_ext);
    
    // Minus 1 to make the offset correct
    $cnt = $file_ext_count - 1;
    
    // The variable will have a value pdf as per the sample file name mentioned above.
    $file_extension = $file_ext[$cnt];
    
    0 讨论(0)
  • 2020-11-21 23:09

    You can get all file extensions in a particular folder and do operations with a specific file extension:

    <?php
        $files = glob("abc/*.*"); // abc is the folder all files inside folder
        //print_r($files);
        //echo count($files);
        for($i=0; $i<count($files); $i++):
             $extension = pathinfo($files[$i], PATHINFO_EXTENSION);
             $ext[] = $extension;
             // Do operation for particular extension type
             if($extension=='html'){
                 // Do operation
             }
        endfor;
        print_r($ext);
    ?>
    
    0 讨论(0)
  • 2020-11-21 23:10

    Use substr($path, strrpos($path,'.')+1);. It is the fastest method of all compares.

    @Kurt Zhong already answered.

    Let's check the comparative result here: https://eval.in/661574

    0 讨论(0)
  • 2020-11-21 23:11

    This will work

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    
    0 讨论(0)
  • 2020-11-21 23:15

    The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.

    $file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
    echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html
    
    0 讨论(0)
  • 2020-11-21 23:15

    IMO, this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens):

    $ext     = explode('.', $filename); // Explode the string
    $ext_len = count($ext) - 1; // Count the array -1 (because count() starts from 1)
    $my_ext  = $ext[$ext_len]; // Get the last entry of the array
    
    echo $my_ext;
    
    0 讨论(0)
提交回复
热议问题