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

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


当前回答

作为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"

你必须知道扩展提前删除它。

然而,由于您的问题表明您需要获得扩展名和基名,我认为Pekka的答案是最有用的,因为它将为您提供有关路径和文件的任何信息,只需一个本地函数。

其他回答

作为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"

你必须知道扩展提前删除它。

然而,由于您的问题表明您需要获得扩展名和基名,我认为Pekka的答案是最有用的,因为它将为您提供有关路径和文件的任何信息,只需一个本地函数。

你可以这样写

$filename = current(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

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

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

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

解释

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

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

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