2012-07-26 67 views
0

我有這個PHP代碼可以將文件從一個目錄複製到另一個目錄,但它的工作原理非常棒,但是,如何僅複製以字母「AUW」(減引號)結尾的文件?請記住,該文件是無擴展名的,所以它真的以字母AUW結尾。PHP只複製以字母結尾的文件AUW

複製後我不希望文件從源文件夾中刪除。

// Get array of all source files 
$files = scandir("sourcefolder"); 
// Identify directories 
$source = "sourcefolder/"; 
$destination = "destinationfolder/"; 
// Cycle through all source files 
foreach ($files as $file) { 
    if (in_array($file, array(".",".."))) continue; 
    // If we copied this successfully, mark it for deletion 
    if (copy($source.$file, $destination.$file)) { 
    $delete[] = $source.$file; 
    } 
} 
// Delete all successfully-copied files 
foreach ($delete as $file) { 
    unlink($file); 
} 

回答

2
foreach ($files as $file) { 
    if (in_array($file, array(".",".."))) continue; 
    if (!endsWith($file, "AUW")) continue; 
    // If we copied this successfully, mark it for deletion 
    if (copy($source.$file, $destination.$file)) { 
    // comment the following line will not add the files to the delete array and they will 
    // not be deleted 
    // $delete[] = $source.$file; 
    } 
} 

// comment the followig line of code since we dont want to delete 
// anything 
// foreach ($delete as $file) { 
// unlink($file); 
// } 

function endsWith($haystack, $needle) 
{ 
    $length = strlen($needle); 
    if ($length == 0) return true; 

    return (substr($haystack, -$length) === $needle); 
} 
+0

是的,你是對的,我會更新我的答案。 – 2012-07-26 16:02:04

+0

對不起,我刪除了評論,因爲我遇到了新行和代碼標籤的問題。你的代碼現在工作正常。 – 2012-07-26 16:03:59

0

Google搜索太難了嗎? 我給你一個提示 - 使用substr(),看看最後的3個字母是「AUW」

AH

+0

這很好,但我如何在我的情況下使用substr與foreach? – 2012-07-26 14:54:15

2

你可以使用函數glob

foreach (glob("*AUW") as $filename) { 
    // do the work... 
} 
1

使用substr() method搶到最後三個文件名的字母。這將返回一個可用於邏輯比較的字符串。

if(substr($file, -3) == 'AUW') 
{ 
    // Process files according to your exception. 
} 
else 
{ 
    // If we copied this successfully, mark it for deletion 
    if (copy($source.$file, $destination.$file)) { 
    $delete[] = $source.$file; 
} 
相關問題