SPLFileInfo:获取不带扩展名的文件名

编程入门 行业动态 更新时间:2024-10-28 16:23:05
本文介绍了SPLFileInfo:获取不带扩展名的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在访问SPLFileInfo对象中的许多文件.我看到了一种获取路径,文件名甚至文件扩展名的方法.有没有办法获取不带扩展名的文件名?这是我一直在使用的代码,但我希望得到一些更优雅的东西.是否有开箱即用的解决方案?

I'm accessing a number of files in the SPLFileInfo object. I see a way to get the path, filename, and even extension of the file. Is there a way to get the filename without extension? Here's the code I've been working with but I'm hoping to get something more elegant. Is there an out of the box solution?

$file = new SplFileInfo("path/to/file.txt.zip"); echo 'basename: '.$file->getBasename(); echo PHP_EOL; echo 'filename: '.$file->getFilename(); echo PHP_EOL; echo 'extension: '.$file->getExtension(); echo PHP_EOL; echo 'basename w/o extension: '.$file->getBasename('.'.$file->getExtension()); >>OUTPUT >>basename: file.txt.zip >>filename: file.txt.zip >>extension: zip >>basename w/o extension: file.txt

推荐答案

我来晚了,所有功劳都应该归功于@salathe,这是第一位帮助OP的人,但这是用于basename函数的PHP手册链接.基本上,您会得到扩展名,然后在点号前加上.,最后使用basename函数来获取名称,如下所示:

I'm late and all the credits should go to @salathe being the first helping the OP, but here's the link to PHP manual for basename function. Basically, you get the extension, then prepend a dot . and finally use the basename function to get the name, like this:

$file->getBasename('.' . $file->getExtension())

为了快速阅读,这是PHP手册页的示例:

For fast reading, here's the PHP manual page's example:

$info = new SplFileInfo('file.txt'); var_dump($info->getBasename()); $info = new SplFileInfo('/path/to/file.txt'); var_dump($info->getBasename()); $info = new SplFileInfo('/path/to/file.txt'); var_dump($info->getBasename('.txt'));

输出:

string(8) "file.txt" string(8) "file.txt" string(4) "file"

更多推荐

SPLFileInfo:获取不带扩展名的文件名

本文发布于:2023-11-02 18:12:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553062.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:扩展名   不带   文件名   SPLFileInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!