本文介绍了在上载的文件中用下划线替换空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a basic script that allows my site members to upload short samples of their compositions for customers to listen to.

某些文件名中的空格显然会在尝试播放样本时引起问题.在上载到temp目录和将文件移动到"samples"目录之间,是否可以用下划线替换这些空格?

Some file names have spaces which obviously causes problems when trying to play the samples. Is there a way to replace these spaces with underscores between uploading to the temp directory and moving the file to the 'samples' directory?

<?
            $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;
              }
              }
            }
?>

推荐答案

此行之后:

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

写:

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

hello  world.mp3 这样的文件名(两个空格)会以hello__world.mp3(两个下划线)的形式出现,为避免这种情况,您可以执行以下操作:

A filename like hello  world.mp3 (two spaces) would come out as hello__world.mp3 (two underscores), to avoid this you could do this instead:

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

这篇关于在上载的文件中用下划线替换空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:21