PHP,获取没有文件扩展名的文件名我有这个PHP代码:function ShowFileExtension($filepath){
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
if(count($pattern) > 1)
{
$filenamepart = $pattern[count($pattern)-1][0];
preg_match('/[^?]*/', $filenamepart, $matches);
return strtolower($matches[0]);
}}如果我有一个名为的文件my.zip,则此函数返回.zip。我想反过来,我希望函数在my没有扩展名的情况下返回。该文件只是变量中的一个字符串。
3 回答
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
幕布斯6054654
TA贡献1876条经验 获得超7个赞
不需要这一切。检查pathinfo(),它为您提供路径的所有组件。
手册中的示例:
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0
输出代码:
/www/htdocs
index.html
html
index
或者你只能获得某些部分,如:
echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
![?](http://img1.sycdn.imooc.com/533e4c7b00013f3c02400205-100-100.jpg)
心有法竹
TA贡献1866条经验 获得超5个赞
作为替代方案pathinfo(),您可以使用
basename() - 返回路径的文件名组件
PHP手册中的示例
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
你必须提前知道扩展名才能删除它。
- 3 回答
- 0 关注
- 883 浏览
添加回答
举报
0/150
提交
取消