如何更改图像名称,并在上传时将“ - ”替换为空格。

问题描述:

我使用此代码如何更改图像名称,并在上传时将“ - ”替换为空格。

<form action="upload.php" method="post" enctype="multipart/form-data"> 
Select image to upload: 
<input type="file" name="fileToUpload" id="fileToUpload"> 
<input type="submit" value="Upload Image" name="submit"> 
</form> 

PHP上传图片用PHP:

<?php 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 



if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], 
$target_file)) { 
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
} else { 
    echo "Sorry, there was an error uploading your file."; 
} 
} 
?> 

我想:如果我上传了一个名为“新York.jpg”的形象,名称被改为“新York.jpg”

+0

使用PHP的'rename'功能 – Akintunde007

+0

如何脚本将检测的空间和地点 “ - ” 代替空间? –

+0

'move_uploaded_file'确实已经重命名了文件,所以只需要清理'$ target_file'就可以了......'str_replace'或'preg_replace'将会运行良好 – Kazz

在你的代码,在这里:

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 

地址:

$target_file = str_replace(' ', '-', $target_file); 

更换

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 

与此2号线,

$target_filename = str_replace(' ', '_', basename($_FILES["fileToUpload"]["name"])); 
$target_file = $target_dir . $target_filename;