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

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


当前回答

你可以这样写

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

如果之前没有使用,这些函数将返回当前数组元素。

其他回答

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

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

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

在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"

你可以这样写

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

如果之前没有使用,这些函数将返回当前数组元素。

如果文件名使用点,你可能会得到错误的输出。 我会使用@Gordon方法,但也获得扩展,所以basename函数适用于所有扩展,像这样:

$path = "/home/httpd/html/index.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

$file = basename($path, ".".$ext); // $file is set to "index"

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

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

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

解释

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