How to remove extension from string (only real extension!)

Php

Php Problem Overview


I'm looking for a small function that allows me to remove the extension from a filename.

I've found many examples by googling, but they are bad, because they just remove part of the string with "." . They use dot for limiter and just cut string.

Look at these scripts,

$from = preg_replace('/\.[^.]+$/','',$from);

or

 $from=substr($from, 0, (strlen ($from)) - (strlen (strrchr($filename,'.'))));

When we add the string like this:

> This.is example of somestring

It will return only "This"...

The extension can have 3 or 4 characters, so we have to check if dot is on 4 or 5 position, and then remove it.

How can it be done?

Php Solutions


Solution 1 - Php

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

>pathinfo — Returns information about a file path

$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'

Solution 2 - Php

Try this one:

$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);

So, this matches a dot followed by three or four characters which are not a dot or a space. The "3 or 4" rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.

Solution 3 - Php

From the manual, pathinfo:

<?php
    $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"; // Since PHP 5.2.0
?>

It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg as /path/to/my/file.jpg.

Solution 4 - Php

Use PHP basename()

(PHP 4, PHP 5)

var_dump(basename('test.php', '.php'));

Outputs: string(4) "test"

Solution 5 - Php

This is a rather easy solution and will work no matter how long the extension or how many dots or other characters are in the string.

$filename = "abc.def.jpg";

$newFileName = substr($filename, 0 , (strrpos($filename, ".")));

//$newFileName will now be abc.def

Basically this just looks for the last occurrence of . and then uses substring to retrieve all the characters up to that point.

It's similar to one of your googled examples but simpler, faster and easier than regular expressions and the other examples. Well imo anyway. Hope it helps someone.

Solution 6 - Php

Recommend use: pathinfo with PATHINFO_FILENAME

$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);

Solution 7 - Php

You could use what PHP has built in to assist...

$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);

Though if you are only dealing with a filename (.somefile.jpg), you will get...

> ./somefile

See it on CodePad.org

Or use a regex...

$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);

See it on CodePad.org

If you don't have a path, but just a filename, this will work and be much terser...

$withoutExt = pathinfo($path, PATHINFO_FILENAME);

See it on CodePad.org

Of course, these both just look for the last period (.).

Solution 8 - Php

The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.

$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);

Solution 9 - Php

> I found many examples on the Google but there are bad because just remove part of string with "."

Actually that is absolutely the correct thing to do. Go ahead and use that.

The file extension is everything after the last dot, and there is no requirement for a file extension to be any particular number of characters. Even talking only about Windows, it already comes with file extensions that don't fit 3-4 characters, such as eg. .manifest.

Solution 10 - Php

There are a few ways to do it, but i think one of the quicker ways is the following

// $filename has the file name you have under the picture
$temp = explode( '.', $filename );
$ext = array_pop( $temp );
$name = implode( '.', $temp );

Another solution is this. I havent tested it, but it looks like it should work for multiple periods in a filename

$name = substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

Also:

$info = pathinfo( $filename );
$name = $info['filename'];
$ext  = $info['extension'];

// Or in PHP 5.4, i believe this should work
$name = pathinfo( $filename )[ 'filename' ];

In all of these, $name contains the filename without the extension

Solution 11 - Php

$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);

Output:

this-is.file.name

Solution 12 - Php

As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me...

function string_pop($string, $delimiter){
    $a = explode($delimiter, $string);
    array_pop($a);
    return implode($delimiter, $a);
}

Usage:

$filename = "pic.of.my.house.jpeg";
$name = string_pop($filename, '.');
echo $name;

Outputs:

pic.of.my.house  (note it leaves valid, non-extension "." characters alone)

In action:

http://sandbox.onlinephpfunctions.com/code/5d12a96ea548f696bd097e2986b22de7628314a0

Solution 13 - Php

This works when there is multiple parts to an extension and is both short and efficient:

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

Solution 14 - Php

You can set the length of the regular expression pattern by using the {x,y} operator. {3,4} would match if the preceeding pattern occurs 3 or 4 times.

But I don't think you really need it. What will you do with a file named "This.is"?

Solution 15 - Php

Use this:

strstr('filename.ext','.',true);
//result filename

Solution 16 - Php

Try to use this one. it will surely remove the file extension.

$filename = "image.jpg";
$e = explode(".", $filename);
foreach($e as $key=>$d)
{
if($d!=end($e)
{

$new_d[]=$d; 
}

 }
 echo implode("-",$new_t);  // result would be just the 'image'

Solution 17 - Php

EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):

$name = basename($filename, '.' . end(explode('.', $filename)));

Cheers ;)

Solution 18 - Php

Landed on this page for looking for the fastest way to remove the extension from a number file names from a glob() result.

So I did some very rudimentary benchmark tests and found this was the quickest method. It was less than half the time of preg_replace():

$result = substr($fileName,0,-4);

Now I know that all of the files in my glob() have a .zip extension, so I could do this.

If the file extension is unknown with an unknown length, the following method will work and is still about 20% faster that preg_replace(). That is, so long as there is an extension.

$result = substr($fileName,0,strrpos($fileName,'.'));

The basic benchmark test code and the results:

$start = microtime(true);

$loop = 10000000;
$fileName = 'a.LONG-filename_forTest.zip';
$result;

// 1.82sec preg_replace() unknown ext
//do {
//    $result = preg_replace('/\\.[^.\\s]{3,4}$/','',$fileName);
//} while(--$loop);

// 1.7sec preg_replace() known ext
//do {
//    $result = preg_replace('/.zip$/','',$fileName);
//} while(--$loop);

// 4.57sec! - pathinfo
//do {
//    $result = pathinfo($fileName,PATHINFO_FILENAME);
//} while(--$loop);

// 2.43sec explode and implode
//do {
//    $result = implode('.',explode('.',$fileName,-1));
//} while(--$loop);

// 3.74sec basename, known ext
//do {
//    $result = basename($fileName,'.zip');
//} while(--$loop);

// 1.45sec strpos unknown ext
//do {
//    $result = substr($fileName,0,strrpos($fileName,'.'));
//} while(--$loop);

// 0.73sec strpos - known ext length
do {
    $result = substr($fileName,0,-4);
} while(--$loop);

var_dump($fileName);
var_dump($result);
echo 'Time:['.(microtime(true) - $start).']';

exit;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcView Question on Stackoverflow
Solution 1 - PhpTimo HuovinenView Answer on Stackoverflow
Solution 2 - PhpnickfView Answer on Stackoverflow
Solution 3 - PhpErikView Answer on Stackoverflow
Solution 4 - PhpYasenView Answer on Stackoverflow
Solution 5 - PhpwprenisonView Answer on Stackoverflow
Solution 6 - PhpAlexView Answer on Stackoverflow
Solution 7 - PhpalexView Answer on Stackoverflow
Solution 8 - PhpEmaneguxView Answer on Stackoverflow
Solution 9 - PhpbobinceView Answer on Stackoverflow
Solution 10 - PhpAschererView Answer on Stackoverflow
Solution 11 - PhpAbhishekView Answer on Stackoverflow
Solution 12 - PhpjbobbinsView Answer on Stackoverflow
Solution 13 - PhpDan BrayView Answer on Stackoverflow
Solution 14 - PhpYour Common SenseView Answer on Stackoverflow
Solution 15 - PhpShintadoniku AlyssaView Answer on Stackoverflow
Solution 16 - PhpGilbert AldavaView Answer on Stackoverflow
Solution 17 - PhpandclView Answer on Stackoverflow
Solution 18 - PhpTiggerView Answer on Stackoverflow