barkster Posted August 9, 2007 Share Posted August 9, 2007 I have a filename string that I need to strip out the last 5 character off the filename preserving the extension. Can anyone help me with this? Thanks Example: largefile12398.jpg would become largefile.jpg Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/ Share on other sites More sharing options...
wsantos Posted August 9, 2007 Share Posted August 9, 2007 You could do a rough replacement for($num=0;$num<=9;$num++) str_replace($num,"",$string); Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/#findComment-319587 Share on other sites More sharing options...
barkster Posted August 9, 2007 Author Share Posted August 9, 2007 Well that would work in theory but I forgot to mention there could be numbers in the rest of the name. Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/#findComment-319592 Share on other sites More sharing options...
barkster Posted August 9, 2007 Author Share Posted August 9, 2007 I've been playing with it more and this is what I've come up with but I was hoping for simpler solution function newfilename($filename) { $len = strlen($filename)-9; $string = substr($filename,0,$len); $ext = explode('.',$filename); $ext = $ext[count($ext)-1]; return $string . "." . $ext; } Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/#findComment-319606 Share on other sites More sharing options...
Orio Posted August 9, 2007 Share Posted August 9, 2007 Here are two other options for you: <?php function newname($filename) { $arr = explode(".", $filename); $arr[count($arr)-2] = substr($arr[count($arr)-2], 0, -5); return implode(".", $arr); } ?> <?php function newname2($filename) { $ext = strrchr($filename, "."); $filename = substr($filename, 0, -(strlen($ext)+5)); return $filename.$ext; } ?> Both tested and they work even with strings that have more than one dot in them. Orio. Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/#findComment-319615 Share on other sites More sharing options...
barkster Posted August 9, 2007 Author Share Posted August 9, 2007 Cool, those look better than my hack. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/64128-trim-string-with-pattern/#findComment-319619 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.