开发者

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

开发者 https://www.devze.com 2023-01-23 13:28 出处:网络
I have a script to upload files with PHP. I already do some cleaning to remove ugly characters. I would also like to to rem开发者_高级运维ove dots in the filename, EXCEPT for the last one, which indi

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

I would also like to to rem开发者_高级运维ove 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号