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

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


当前回答

几乎所有上述解决方案都显示从变量$path获取文件名

下面的代码段将获得当前执行的不带扩展名的文件名

echo pathinfo(basename($_SERVER['SCRIPT_NAME']), PATHINFO_FILENAME);

解释

$_SERVER['SCRIPT_NAME']包含当前脚本的路径。

其他回答

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

pathinfo($path, PATHINFO_FILENAME);

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

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

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

文件扩展名提取:

File Name = subrotobiswas.jpg
$fileExtension = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION); //Output: jpg
$newNameOfFileWithoutExtension = basename( $_FILES["fileToUpload"]["name"], $fileExtension ); //Output: subrotobiswas
$fullFileName = $newNameOfFileWithoutExtension . "." .$fileExtension; // Output: subrotobiswas.jpg

在我的例子中,我使用下面的方法。我不关心它的延伸是什么。: D 我想这对你有帮助

$exploded_filepath = explode(".", $filepath_or_URL);
$extension = end($exploded_filepath);
echo basename($filepath_or_URL, ".".$extension ); //will print out the the name without extension.

如果你不知道你有哪个扩展,那么你可以试试这个:

$ext = strtolower(substr('yourFileName.ext', strrpos('yourFileName.ext', '.') + 1));
echo basename('yourFileName.ext','.'.$ext); // output: "youFileName" only

考虑到所有的可能性:

image.jpg // output: "image"
filename.image.png // output: "filename.image"
index.php // output: "index"