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

php

Question

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?

1
122
4/19/2013 6:11:01 PM

Accepted Answer

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.

162
6/19/2014 6:35:43 AM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon