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
https://forums.phpfreaks.com/topic/31468-solved-selective-str_replace-method/
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.
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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.