Jump to content

[SOLVED] Selective str_replace Method?


judeddokoinu

Recommended Posts

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.
Link to comment
Share on other sites

[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.
Link to comment
Share on other sites

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)
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.