如何将多个.txt 文件按PHP 中的名称移动到文件夹中?

How to move several .txt files into folders according to their names in PHP?

我有一个包含 3 个子文件夹和 .txt 文件的文件夹,名称如下:

我愿意:

我已经完成了这个功能,但是它不起作用......我的错误在哪里?

<?php

function deplacementFile( $path ) {

   $dir    = './test/';
   $allFiles = scandir($dir);

   foreach($allFiles as $file) {

        if (!in_array($file,array(".","..","FR", "ES", "PT")))
      { 

      $file = $dir.$file;
      $filename = basename( $file );

       //read the entire string
       $str = file_get_contents( $file );

       if ( strpos( $filename, 'A500_' ) === 0 ) {
        $dossierDestination1 = './test/FR/';
        if(!copy($dir, $dossierDestination1)) { 
            echo "error copy";
            } else { 
            if(!unlink($dir)) { 
                echo "error unlink"; 
            } 
        }
      }
        else if ( strpos( $filename, 'A700_' ) === 0 ) {
            $dossierDestination2 = './test/ES/';
            if(!copy($dir, $dossierDestination2)) { 
                echo "error copy";
                } else { 
                if(!unlink($dir)) { 
                    echo "error unlink"; 
                } 
            }
          }

       else if ( strpos( $filename, 'A900_' ) === 0 ) {
        $dossierDestination3 = './test/PT/';
        if(!copy($dir, $dossierDestination3)) { 
            echo "error copy";
            } else { 
            if(!unlink($dir)) { 
                echo "error unlink"; 
            } 
        }
      }
            else {

           return false;
       }
    }
  }
}

deplacementFile( './test/' ); 

echo "Successfully completed!";
?>

这是您脚本的升级版本:

function deplacementFile( $path ) {

    $dir    = './test/';
    $allFiles = scandir($dir);

    foreach($allFiles as $file) {
        if (!in_array($file,array(".","..","FR", "ES", "PT")))
        { 
            // $file - is PATH to copied file
            $file = $dir.$file;
            // $filename - is the name of file being copied
            $filename = basename( $file );

            $paths = [
                'A500_' => './test/FR/',
                'A700_' => './test/ES/',
                'A900_' => './test/PT/',
            ];
            foreach ($paths as $key => $dest) {
                if (strpos( $filename, $key ) === 0) {
                    // copy from PATH to new path which is `dest and filename`
                    if(!copy($file, $dest . $filename)) { 
                        echo "error copy";
                    } else { 
                        if(!unlink($file)) { 
                            echo "error unlink"; 
                        } 
                    }
                    break;
                }
            }
        }
    }
}

此外,考虑 rename 哪个 移动 文件,参数是相同的,但你不需要 unlink.