我有这样的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。

文件只是变量中的字符串。


当前回答

当扩展有多个部分时,现有的解决方案就会失败。下面的函数适用于多个部分,一个完整的路径或一个文件名:

function removeExt($path)
{
    $basename = basename($path);
    return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}

echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file

其他回答

不知道扩展名的文件名:

$basename = substr($filename, 0, strrpos($ fi里程碑,");

@Gordon basename将工作很好,如果你知道扩展,如果你不知道,你可以使用爆炸:

$filename = end(explode(".", $file));

在1行中只返回没有任何扩展名的文件名:

$path = "/etc/sudoers.php";    
print array_shift(explode(".", basename($path)));
// will print "sudoers"

$file = "file_name.php";    
print array_shift(explode(".", basename($file)));
// will print "file_name"

你的答案是下面隐藏到php文件扩展名的完美解决方案。

<?php
    $path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    echo basename($path, ".php");
?>

https://php.net/manual/en/function.pathinfo.php

pathinfo($path, PATHINFO_FILENAME);

简单功能测试:https://ideone.com/POhIDC