Get file name without file extension in PHP

PHP Dec 29, 2020 Viewed 51 Comments 0

This article introduces two ways to get file name without file extension in PHP.

1. Using regular expressions

Use basename to get the trailing name component of path, and then delete the extension with preg_replace.

function getNameWithoutExtFromStr($filePath)
{
    if (strpos($filePath, "/") !== false) {
        $filePath = basename($filePath);
    }
    return preg_replace("/\.[^.]+$/", "", $filePath);
}

2. Using pathinfo

Refer to pathinfo api, set the PATHINFO_FILENAME option for the second parameter of this method.

function getNameWithoutExtFromStr($filePath)
{
    return pathinfo($filePath, PATHINFO_FILENAME);
}

Using like bellow.

echo getNameWithoutExtFromStr("test.zip");    // test
echo getNameWithoutExtFromStr("http://www.baidu.com/name.zip?key=val");    // name
Updated Dec 29, 2020