[英]PHP replace spaces with dashes in uploaded image and rename/save it?
我有一个用于上传图像的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
但这是错误的。
有人可以建议这个问题吗?
提前致谢。
用户正则表达式,可以使用连字符更改多个空格或单个空格。
$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath);
实际上$targetPath2 = str_replace(" ","-",$targetPath);
也可以。 但是您必须在if条件之前编写此代码。
$targetPath2 = preg_replace('#[ -]+#', '-', $targetPath);
if(move_uploaded_file($sourcePath,$targetPath2)) {
//do your stuffs
}
试试这个代码:
<?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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.