Page 1 of 1

Remove everything after last .

Posted: Thu Nov 16, 2006 12:34 pm
by shiznatix
I need a regex that will remove everything after the last . found in a string. Basically, I am removing the file extension from a file that is being uploaded.

Can anyone help?

Posted: Thu Nov 16, 2006 12:45 pm
by Luke
I wonder if this would be faster than a regex (untested):

Code: Select all

$string = 'filename.something.txt';
$apart = explode('.', $string);
$ext = array_pop($apart);
$filename = implode('.', $apart);

Posted: Thu Nov 16, 2006 12:46 pm
by Burrito
if you decide to go with regex, something like this should work:

Code: Select all

$pattern = "/\.[a-z0-9]+$/i";

Posted: Thu Nov 16, 2006 1:38 pm
by Chris Corbyn

Code: Select all

echo substr($string, 0, strrpos(".", $string));

Posted: Thu Nov 16, 2006 1:44 pm
by Burrito
d11wtq wrote:

Code: Select all

echo substr($string, 0, strrpos(".", $string));
oooo...I like that one, but make sure you reverse the order of the arguments in strrpos :wink:

Code: Select all

echo substr($string, 0, strrpos($string,"."));

Posted: Thu Nov 16, 2006 1:49 pm
by Chris Corbyn
Burrito wrote:but make sure you reverse the order of the arguments in strrpos :wink:
:oops:

Posted: Thu Nov 16, 2006 1:57 pm
by Luke
Burrito wrote:oooo...I like that one, but make sure you reverse the order of the arguments in strrpos :wink:
yea it didn't work for me... didn't bother to check order of arguments though

Posted: Fri Dec 08, 2006 3:40 pm
by kaisellgren

Code: Select all

$str = "filename.php";
$str = preg_replace("/(\\.).*/","\\1",$str); // filename.

Posted: Fri Dec 08, 2006 3:52 pm
by RobertGonzalez
Burrito wrote:
d11wtq wrote:

Code: Select all

echo substr($string, 0, strrpos(".", $string));
oooo...I like that one, but make sure you reverse the order of the arguments in strrpos :wink:

Code: Select all

echo substr($string, 0, strrpos($string,"."));
Let's see, was that search for a 'needle' in a 'haystack' or search the 'haystack' for a 'needle'? Hmmm...