简体   繁体   中英

PHP: How to remove unnecessary dots in filename on file upload?

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM