judeddokoinu Posted December 21, 2006 Share Posted December 21, 2006 I have a user upload script which has the following statement:[code]$file = str_replace('.', '_', $file);[/code]Which replaces dots in the filename with underscores BUT I would like to leave the last dot (the one before the extension) since I do not know beforehand how many characters the file extension will have. Thus, I can not simply count back 3 characters and add a dot after replacing them.The only thing I can think of is to do the str_replace(), and then come back and replace the last underscore found in the string with a dot, but I'm not entirely sure how to replace the last one.Is there a method to count how many dots are in the filename string, subtract 1 and then replace all but the last?What's the solution here? Thanks. :D**EDIT**Just tried out:[code]$numberdots = substr_count($file, '.') - 1;$file = preg_replace('/./', '_', $file, $numberdots);[/code]But that did not work either. My filename went from: full.logo.bar_copy.jpg to __ll.logo.bar_copy.jpg which doesn't make any sense to me, but still got dots in it lol. Quote Link to comment Share on other sites More sharing options...
Orio Posted December 21, 2006 Share Posted December 21, 2006 [code]<?php//$filename holds the filename$ext = substr(strrchr($filename,"."),1);$new = str_replace(".","_",substr($filename,0, -(strlen($ext)+1))).".".$ext;?>[/code]Have fun :)Orio.EDIT- A bit faster way:[code]<?php//$filename holds the filename$ext = strrchr($filename,".");$new = str_replace(".","_",substr($filename,0, -strlen($ext))).$ext;?>[/code]Orio. Quote Link to comment Share on other sites More sharing options...
trq Posted December 21, 2006 Share Posted December 21, 2006 Damn.... look at mine![code=php:0]function replace_except_last($search,$replace,$subject) { for ($i = 0; $i < strlen($subject); $i++) { if ($subject{$i} == $search) { if ($i != strrpos($subject,$search)) { $s{$i} = $replace; } } } }[/code]there allways a better way huh. (And mine usually isn't it) Quote Link to comment Share on other sites More sharing options...
judeddokoinu Posted December 21, 2006 Author Share Posted December 21, 2006 Well, thanks for the help guys. I was banging my head on the desk at that one. I was about to use an explode and loop through and well, that way was much easier. I didn't even think of removing the extension like that. Quote Link to comment 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.