我有一个用于上传图像的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
,但这是错误的。
有人可以就此问题提供建议吗?
预先感谢。
尝试以下代码:
<?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);
用户正则表达式,这可以用连字符更改多个空间或单个空间。
$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath);
实际上$targetPath2 = str_replace(" ","-",$targetPath);
也有效。但是您必须在IF条件之前编写此代码。
$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath);
if(move_uploaded_file($sourcePath,$targetPath2)) {
//do your stuffs
}