1

I have a script to upload files with PHP. I already do some cleaning to remove ugly characters.

I would also like to to remove dots in the filename, EXCEPT for the last one, which indicates the file extension.

Anyone has an idea how I could do that.?

For example, how would you get

$filename = "water.fall_blue.sky.jpg";
$filename2 = "water.fall_blue.sky.jpeg";

to return this in both cases..?

water.fall_blue.sky
pnichols
  • 2,198
  • 4
  • 24
  • 29
  • 3
    what if I want to upload archive.tar.gz? – Gordon Nov 03 '10 at 16:31
  • possible duplicate of [How to extract a file extension in PHP ?](http://stackoverflow.com/questions/173868/how-to-extract-a-file-extension-in-php) and [Fastest Way to replace String in PHP](http://stackoverflow.com/questions/3869829/fastest-way-to-replace-string-in-php) – Gordon Nov 03 '10 at 16:47

3 Answers3

10

Use pathinfo() to extract the file name (the "filename" array element is available since PHP 5.2); str_replace() all the dots out of it; and re-glue the file extension.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
4

Here's an example of how this can be done:

<?php
$string = "really.long.file.name.txt";
$lastDot = strrpos($string, ".");
$string = str_replace(".", "", substr($string, 0, $lastDot)) . substr($string, $lastDot);
?>

It converts filenames like so:

really.long.file.name.txt -> reallylongfilename.txt

Check here: example

[Edit] Updated script, dot position is cached now

Cpt. eMco
  • 565
  • 4
  • 13
1

FILENAME = this/is(your,file.name.JPG

$basename=basename($_FILES['Filedata']['name']);

$filename=pathinfo($basename,PATHINFO_FILENAME);
$ext=pathinfo($basename,PATHINFO_EXTENSION);

//replace all these characters with an hyphen
$repar=array(".",","," ",";","'","\\","\"","/","(",")","?");

$repairedfilename=str_replace($repar,"-",$filename);
$cleanfilename=$repairedfilename.".".strtolower($ext);

RESULT = this-is-your-file-name.jpg

MeKoo Solutions
  • 271
  • 6
  • 5