How do I get a file extension in PHP?

前端 未结 28 2291
一向
一向 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:05

    Use

    str_replace('.', '', strrchr($file_name, '.'))
    

    for a quick extension retrieval (if you know for sure your file name has one).

    0 讨论(0)
  • Sometimes it's useful to not to use pathinfo($path, PATHINFO_EXTENSION). For example:

    $path = '/path/to/file.tar.gz';
    
    echo ltrim(strstr($path, '.'), '.'); // tar.gz
    echo pathinfo($path, PATHINFO_EXTENSION); // gz
    

    Also note that pathinfo fails to handle some non-ASCII characters (usually it just suppresses them from the output). In extensions that usually isn't a problem, but it doesn't hurt to be aware of that caveat.

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

    If you are looking for speed (such as in a router), you probably don't want to tokenize everything. Many other answers will fail with /root/my.folder/my.css

    ltrim(strrchr($PATH, '.'),'.');
    
    0 讨论(0)
  • 2020-11-21 23:07

    Sorry... "Short Question; But NOT Short Answer"

    Example 1 for PATH

    $path = "/home/ali/public_html/wp-content/themes/chicken/css/base.min.css";
    $name = pathinfo($path, PATHINFO_FILENAME);
    $ext  = pathinfo($path, PATHINFO_EXTENSION);
    printf('<hr> Name: %s <br> Extension: %s', $name, $ext);
    

    Example 2 for URL

    $url = "//www.example.com/dir/file.bak.php?Something+is+wrong=hello";
    $url = parse_url($url);
    $name = pathinfo($url['path'], PATHINFO_FILENAME);
    $ext  = pathinfo($url['path'], PATHINFO_EXTENSION);
    printf('<hr> Name: %s <br> Extension: %s', $name, $ext);
    

    Output of example 1:

    Name: base.min
    Extension: css
    

    Output of example 2:

    Name: file.bak
    Extension: php
    

    References

    1. https://www.php.net/manual/en/function.pathinfo.php

    2. https://www.php.net/manual/en/function.realpath.php

    3. https://www.php.net/manual/en/function.parse-url.php

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

    pathinfo()

    $path_info = pathinfo('/foo/bar/baz.bill');
    
    echo $path_info['extension']; // "bill"
    
    0 讨论(0)
  • 2020-11-21 23:08

    Here is an example. Suppose $filename is "example.txt",

    $ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));
    

    So $ext will be ".txt".

    0 讨论(0)
提交回复
热议问题