用上载文件中的下划线替换空格

时间:2012-05-15 17:31:22

标签: php

我有一个基本脚本,允许我的网站成员上传其作品的简短样本供客户收听。

某些文件名有空格,在尝试播放样本时显然会出现问题。有没有办法在上传到临时目录和将文件移动到'samples'目录之间用下划线替换这些空格?

<?
            $url = "http://domain.com/uploads/samples/";
            //define the upload path
            $uploadpath = "/home/public_html/uploads/samples";
            //check if a file is uploaded
             if($_FILES['userfile']['name']) {
              $filename = trim(addslashes($_FILES['userfile']['name']));
            //move the file to final destination
              if(move_uploaded_file($_FILES['userfile']['tmp_name'],
            $uploadpath."/". $filename)) {

              echo "

    bla bla bla, the final html output

            ";

              } else{
                if ($_FILES['userfile']['error'] > 0)
              {
                   switch ($_FILES['userfile']['error'])
                {
                  case 1:  echo 'File exceeded upload_max_filesize';  break;
                  case 2:  echo 'File exceeded max_file_size';  break;
                  case 3:  echo 'File only partially uploaded';  break;
                  case 4:  echo 'No file uploaded';  break;
                }
                exit;
              }
              }
            }
?>

3 个答案:

答案 0 :(得分:12)

这一行之后:

$filename = trim(addslashes($_FILES['userfile']['name']));

写:

$filename = str_replace(' ', '_', $filename);

hello world.mp3 这样的文件名(两个空格)会出现hello__world.mp3(两个下划线),为避免这种情况,你可以这样做:

$filename = preg_replace('/\s+/', '_', $filename);

答案 1 :(得分:0)

$filename = str_replace(' ', '-', trim(addslashes($_FILES['userfile']['name'])));

为什么addslashes?这似乎有点太简单 - 我错过了什么?

答案 2 :(得分:0)

试;

$filename = trim(str_replace(" ","_", $_FILES['userfile']['name']));