Remove everything after last .

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Remove everything after last .

Post 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?
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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);
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

if you decide to go with regex, something like this should work:

Code: Select all

$pattern = "/\.[a-z0-9]+$/i";
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Code: Select all

echo substr($string, 0, strrpos(".", $string));
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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,"."));
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Burrito wrote:but make sure you reverse the order of the arguments in strrpos :wink:
:oops:
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Post by kaisellgren »

Code: Select all

$str = "filename.php";
$str = preg_replace("/(\\.).*/","\\1",$str); // filename.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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...
Post Reply