views:

775

answers:

4

Welcome,

I'm looking for small function what allow me to remove extension from filename.

I found many examples on the Google but there are bad because just remove part of string with "." . They use dot for limitter and just cut string.

Look at this scripts

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

OR

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

When we add sting like this: This.is example of somestring

It will return only "This"...

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

Any idea ?

Regards

+1  A: 

You can set length of the regexp pattern by using {x,y} operator
{3,4} would match if preceeding pattern occurs 3 or 4 times
But I fon't think you really need it. What will you do with a file named "This.is"?

Col. Shrapnel
+7  A: 

From the manual

<?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

Erik
I already checked this.Same mistake as above.Try access "$path_parts['filename']" from T.sec - "xxx" 23 12 32 3 a twym2It will return only T.From above example it shouldn't remove anything !
marc
+1  A: 

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.

nickf
Thank you.Your code working perfect.Regards
marc
A: 

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.

bobince