这是一个问题,你可以在网络上的任何地方看到各种答案:
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
etc.
然而,总是有“最好的方法”,它应该是堆栈溢出。
1) 如果您正在使用(PHP 5>=5.3.6)可以使用SplFileInfo::getExtension-获取文件扩展名
示例代码
<?php
$info = new SplFileInfo('test.png');
var_dump($info->getExtension());
$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());
?>
这将输出
string(3) "png"
string(2) "gz"
2) 如果您正在使用(PHP4>=4.0.3,PHP5),另一种获取扩展名的方法是pathinfo
示例代码
<?php
$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);
$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);
?>
这将输出
string(3) "png"
string(2) "gz"
//EDIT:删除支架
很抱歉“简短的问题;但不是简短的回答”
PATH示例1
$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);
URL示例2
$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);
示例1的输出:
Name: base.min
Extension: css
示例2的输出:
Name: file.bak
Extension: php
工具书类
https://www.php.net/manual/en/function.pathinfo.phphttps://www.php.net/manual/en/function.realpath.phphttps://www.php.net/manual/en/function.parse-url.php