2017-05-27 18 views
0

我有一個我用來上傳圖片的PHP代碼。PHP在上傳的圖像中用空白替換空格並重命名/保存它?

這工作正常。但是,有時候,我上傳的圖片中有空格的名字,像這樣:

image name.png 

我需要做我的PHP代碼的東西,將與破折號替代的空間圖像的名字,像這樣:

image-name.png 

這是我當前的代碼:

<?php 

if(is_array($_FILES)) { 

if(is_uploaded_file($_FILES['userImage']['tmp_name'])) { 

$sourcePath = $_FILES['userImage']['tmp_name']; 

$targetPath = "../../feed-images2/".$_FILES['userImage']['name']; 


if(move_uploaded_file($sourcePath,$targetPath)) { 


$imageUrl = str_replace("../../","http://example-site.com/",$targetPath); 



?> 

<?php echo $imageUrl; ?> 

<?php 
} 
} 
} 
?> 

我試着這樣做:

$targetPath2 = str_replace(" ","-",$targetPath); 

然後嘗試使用變量$targetPath2但這是錯誤的。

請問有人能就這個問題提出建議嗎?

在此先感謝。

+0

一個普遍的線索:顯示器(或登錄)您的變量的內容,檢查的內容是好的。 另外,你有沒有在日誌中出現錯誤? – technico

+2

你正在替換'$ targetpath'中的空格,但你只需要在$ _FILES ['userImage'] ['name']' – niceman

+0

@niceman中替換它們,你確實是一個很好的人。 :) –

回答

0

用戶正則表達式,這可以用連字符更改多個空格或單個空格。

$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath); 

其實$targetPath2 = str_replace(" ","-",$targetPath);也有效。但是你必須在if條件之前編寫這段代碼。

$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath); 
if(move_uploaded_file($sourcePath,$targetPath2)) { 

//do your stuffs 

} 
+0

解決。但爲什麼str_replace不起作用? – Nishakar

0

試試這個代碼:

<?php 
if(is_array($_FILES)) { 
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) { 
$sourcePath = $_FILES['userImage']['tmp_name']; 
$targetPath = "../../feed-images2/".$_FILES['userImage']['name']; 
if(move_uploaded_file($sourcePath,$targetPath)) { 
$imageUrl = str_replace(" ","-",$imageUrl); 
echo $imageUrl; 
} 
} 
} 
?> 

或者你可以使用

$imageUrl = preg_replace('/\s+/', '-', $imageUrl); 
相關問題