2012-07-05 319 views
-4

我有一個關於文件句柄的一個問題,我有:移動文件到特定文件夾

文件: 「馬克,123456,HTCOM.pdf」

「約翰,409721,JESOA.pdf

文件夾:

「馬克,123456」

「馬克,345212」

「馬克,645352」

「約翰,409721」

「約翰,235212」

「約翰,124554」

我需要一個程序來將文件移動到正確的文件夾。 在上面的情況下,我需要比較來自文件和文件夾的第一個和第二個值。如果是相同的我移動文件。

補充到崗位: 我有這樣的代碼,工作的權利,但我需要修改,以檢查名稱和代碼,移動文件... 我很困惑實現功能...

$pathToFiles = 'files folder'; 
$pathToDirs = 'subfolders'; 
foreach (glob($pathToFiles . DIRECTORY_SEPARATOR . '*.pdf') as $oldname) 
{ 
    if (is_dir($dir = $pathToDirs . DIRECTORY_SEPARATOR . pathinfo($oldname, PATHINFO_FILENAME))) 
    { 
     $newname = $dir . DIRECTORY_SEPARATOR . pathinfo($oldname, PATHINFO_BASENAME); 


     rename($oldname, $newname); 
    } 
} 
+1

是的,對不起,我已經發布代碼,也... – user1504222 2012-07-05 14:17:34

回答

0

作爲一個粗略的草稿和東西,將只與您的特定情況下(或相同的命名模式下任何其他情況下)工作,這應該工作:

<?php 
// define a more convenient variable for the separator 
define('DS', DIRECTORY_SEPARATOR); 

$pathToFiles = 'files folder'; 
$pathToDirs = 'subfolders'; 

// get a list of all .pdf files we're looking for 
$files = glob($pathToFiles . DS . '*.pdf'); 

foreach ($files as $origPath) { 
    // get the name of the file from the current path and remove any trailing slashes 
    $file = trim(substr($origPath, strrpos($origPath, DS)), DS); 

    // get the folder-name from the filename, following the pattern "(Name, Number), word.pdf" 
    $folder = substr($file, 0, strrpos($file, ',')); 

    // if a folder exists matching this file, move this file to that folder! 
    if (is_dir($pathToDirs . DS . $folder)) { 
     $newPath = $pathToDirs . DS . $folder . DS . $file; 
     rename($origPath, $newPath); 
    } 
} 
相關問題