簡體   English   中英

使用PHP復制並重命名多個文件

[英]Copy and rename multiple files with PHP

有沒有一種方法可以復制和重命名php中的多個文件,但可以從數組或變量列表中獲取它們的名稱。

我所能找到的最接近的內容是此頁面將文件復制並重命名到同一目錄,而不刪除原始文件

但是此頁面上腳本唯一要做的就是創建第二個文件,並且該名稱已在腳本中預設。

我需要能夠復制和創建多個文件,例如100-200,並從數組中獲取它們的名稱。

如果我有一個名為“ service.jpg”的初始文件,則需要使用數組中的不同名稱多次復制該文件,例如:

$ imgnames = array('倫敦','紐約','西雅圖',); 等等

得到3個單獨的文件的最終結果,分別是“ service-London.jpg”,“ service-New-York.jpg”等。

我確定它應該是一個非常簡單的腳本,但是我當時對PHP的了解確實微不足道。

您可以使用正則表達式來構建新的文件名,如下所示:

$fromFolder = 'Images/folder/';
$fromFile = 'service.jpg';
$toFolder = 'Images/folder/';
$imgnames = array('London', 'New-York','Seattle');

foreach ($imgnames as $imgname) {
    $newFile = preg_replace("/(\.[^\.]+)$/", "-" . $imgname . "$1", $fromFile);
    echo "Copying $fromFile to $newFile";
    copy($fromFolder . $fromFile, $toFolder . $newFile);
}

上面在復制文件時將輸出以下內容:

Copying service.jpg to service-London.jpg
Copying service.jpg to service-New-York.jpg
Copying service.jpg to service-Seattle.jpg

在上面的代碼中,將$fromFolder$toFolder為您的文件夾,如果需要,它們可以是同一文件夾。

您可以采用的一種方法(未經測試)是創建一個類來復制目錄。 您提到您需要獲取目錄中文件的名稱,這種方法將為您處理文件。

它將遍歷一個名稱數組(無論傳遞給它什么),並復制/重命名您選擇的目錄中的所有文件。 您可能想在copy()方法中添加一些檢查( file_exists等),但這肯定會讓您file_exists ,而且很靈活。

// Instantiate, passing the array of names and the directory you want copied
$c = new CopyDirectory(['London', 'New-York', 'Seattle'], 'location/of/your/directory/');

// Call copy() to copy the directory
$c->copy();

/**
 * CopyDirectory will iterate over all the files in a given directory
 * copy them, and rename the file by appending a given name
 */
class CopyDirectory
{
    private $imageNames; // array
    private $directory; // string

    /**
     * Constructor sets the imageNames and the directory to duplicate
     * @param array
     * @param string
     */
    public function __construct($imageNames, $directory)
    {
        $this->imageNames = $imageNames;
        $this->directory = $directory;
    }

    /**
     * Method to copy all files within a directory
     */
    public function copy()
    {   
        // Iterate over your imageNames
        foreach ($this->imageNames as $name) {
            // Locate all the files in a directory (array_slice is removing the trailing ..)
            foreach (array_slice(scandir($this->directory),2) as $file) {
                // Generates array of path information
                $pathInfo = pathinfo($this->directory . $file);

                // Copy the file, renaming with $name appended
                copy($this->directory . $file, $this->directory . $pathInfo['filename'] . '-' . $name .'.'. $pathInfo['extension']);
            }
        }       
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM