How do I get a file extension in PHP?

前端 未结 28 2255
一向
一向 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: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('
    Name: %s
    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('
    Name: %s
    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

提交回复
热议问题