使用PHP复制和重命名多个文件


Copy and rename multiple files with PHP

有没有一种方法可以在php中复制和重命名多个文件,但从数组或变量列表中获取它们的名称。

我能找到的最接近我需要的东西是这个页面复制&将文件重命名到同一目录,而不删除原始文件

但这个页面上的脚本所做的唯一一件事就是创建第二个文件,并且它的名称已经预先设置在脚本中。

我需要能够复制和创建多个文件,比如100-200,并从数组中设置它们的名称。

如果我有一个名为"service.jpg"的初始文件我需要用数组中的不同名称多次复制文件,如下所示:

$imgnames=数组("伦敦"、"纽约"、"西雅图");等

获得名为"serviceLondon.jpg"、"serviceNewYork.jpg"等3个独立文件的最终结果。

我确信这应该是一个非常简单的脚本,但我对PHP的了解在当时真的微不足道。

您可以采用的一种方法(未经测试)是创建一个类来复制目录。您提到您需要获得目录中文件的名称,这种方法将为您处理它。

它将遍历一个名称数组(无论您传递给它什么),并复制/重命名您选择的目录中的所有文件。您可能想在copy()方法(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']);
            }
        }       
    }
}

您可以使用正则表达式来构建新的文件名,如下所示:

$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设置为您的文件夹,如果需要,它们可以是同一个文件夹。