This is a question you can read everywhere on the web with various answers:
$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1
Use
str_replace('.', '', strrchr($file_name, '.'))
for a quick extension retrieval (if you know for sure your file name has one).
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.
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, '.'),'.');
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
https://www.php.net/manual/en/function.pathinfo.php
https://www.php.net/manual/en/function.realpath.php
https://www.php.net/manual/en/function.parse-url.php
pathinfo()
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
Here is an example. Suppose $filename is "example.txt",
$ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));
So $ext will be ".txt".