简体   繁体   English

PHP:如何在文件上传时删除文件名中不必要的点?

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

I have a script to upload files with PHP. 我有一个脚本可以使用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); 使用pathinfo()提取文件名(从PHP 5.2开始,“ filename”数组元素可用); str_replace() all the dots out of it; str_replace()所有点都删除; 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 true.long.file.name.txt-> reallongfilename.txt

Check here: example 在这里检查: 示例

[Edit] Updated script, dot position is cached now [编辑]更新了脚本,现在缓存点位置

FILENAME = this/is(your,file.name.JPG FILENAME = this / is(您的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 结果=这是您的文件名.jpg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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