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

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


当前回答

在我的例子中,我使用下面的方法。我不关心它的延伸是什么。: 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.

其他回答

另一种方法是使用正则表达式。

$fileName = basename($filePath);
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

从最后一个周期中删除。一直到字符串的末尾。

echo pathinfo(__FILE__)['filename']; // since php 5.2

没有必要编写大量的代码。甚至只需一行代码就可以完成。在这里看到的

下面是一行代码,只返回文件名并删除扩展名:

<?php
 echo pathinfo('logo.png')['filename'];
?>

它会打印出来

logo

源代码:删除扩展名,只返回PHP中的文件名

文件扩展名提取:

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

没有必要做这些。检查pathinfo(),它提供了路径的所有组件。

手册中的示例:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0

代码输出:

/www/htdocs
index.html
html
index

或者你可以只得到某些部分,比如:

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html