复制文件、文件夹并替换内容

本文介绍了一种在PHP中复制并替换文件名的方法,包括如何使用`file_get_contents`读取文件内容,通过`strtr`进行字符串替换,并利用`file_put_contents`保存到新文件。同时展示了如何递归复制目录下的所有文件并进行相应的替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 复制PHP文件
 * @param $source 复制源文件夹
 * @param $dest  目标文件夹
 * $name  控制器名称
 */
function copyPhpFile($source,$dest,$table_change){
    $phpfile = file_get_contents($source);
    $phpfile = strtr($phpfile,$table_change);
    file_put_contents($dest, $phpfile);
}
/**
 * 复制html文件夹
 * @param $source 复制源文件夹
 * @param $dest  目标文件夹
 */
function copyHtmlDir($source,$dest,$table_change)
{
    if (!file_exists($dest)) mkdir($dest);
    $handle = opendir($source);
    while (($item = readdir($handle)) !== false) {
         if ($item == '.' || $item == '..') continue;
         $_source = $source . '/' . $item;
         $_dest = $dest . '/' . $item;
         if (is_file($_source)){
//           copy($_source, $_dest);
             $file = file_get_contents($_source);
             $file = strtr($file,$table_change);
             file_put_contents($_dest, $file);
         }
//       if (is_dir($_source)) copydir($_source, $_dest);
    }
    closedir($handle);
}
调用:
                          $source = __DIR__.'\Lists.php';
                          $table_change1 = array('Lists'=>$name[1]);
                          $table_change2 = array('lists'=>$name[1]);
                        copyPhpFile($source,__DIR__.'\\'.$name[1].'.php',$table_change1);
                          copyHtmlDir($_SERVER['DOCUMENT_ROOT'].'\themes\admin\lists',$_SERVER['DOCUMENT_ROOT'].'\themes\admin\\'.$name[1],$table_change2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值