donglie7268 2010-02-02 11:10 采纳率: 100%
浏览 65
已采纳

PHP,获取没有文件扩展名的文件名

I have this PHP code:

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]);
    }
}

If I have a file named my.zip, this function returns .zip.

I want to do the reverse, I want the function to return my without the extension.

The file is just a string in a variable.

  • 写回答

17条回答 默认 最新

  • duanputian5341 2010-02-02 11:13
    关注

    No need for all that. Check out pathinfo(), it gives you all the components of your path.

    Example from the manual:

    $path_parts = pathinfo('/www/htdocs/index.html');
    
    echo $path_parts['dirname'], "
    ";
    echo $path_parts['basename'], "
    ";
    echo $path_parts['extension'], "
    ";
    echo $path_parts['filename'], "
    "; // filename is only since PHP 5.2.0
    

    Output of the code:

    /www/htdocs
    index.html
    html
    index
    

    And alternatively you can get only certain parts like:

    echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(16条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程