PHP如何获取URL地址的后缀名

阅 29

问题

PHP如何获取URL地址的后缀名

答案

使用 pathinfo() 即可获取。

$path_parts = pathinfo('https://www.php7.com.cn/question/10.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";

此代码会输出如下内容:

https://www.php7.com.cn/question
2.html
html
2

详解

单纯使用方法pathinfo()存在一个潜在的问题,当url地址包含hash部分时或包含GET参数时会获取错误,如:

$path_parts = pathinfo('https://www.php7.com.cn/question/10.html?q=keyword#id');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";

输出的extension会包含hashGET参数部分:

https://www.php7.com.cn/question
10.html?q=keyword#id
html?q=keyword#id
10

因此需要剔除hashGET参数部分,修复后的代码如下:

function file_extension($url) {
    $extension_parts = explode('.', $url);
    return preg_split('/\#|\?/', array_pop($extension_parts))[0];
};

echo file_extension('https://www.php7.com.cn/question/10.html'), "\n";
echo file_extension('https://www.php7.com.cn/question/10.html?q=keyword#id'), "\n";

此外,使用JavaScript获取URL地址的后缀名:

var fileExtension = function( url ) {
    return url.split('.').pop().split(/\#|\?/)[0];
}

参考阅读

本题链接:https://www.php7.com.cn/question/10.html
Markdown版本:https://www.php7.com.cn/question/10.md

最后更新: