首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 批次替換相對路徑為絕對路徑:結合 BAT 腳本實現自動化部署

     編輯:PHP 綜合知識

前言

前端專案建構後,靜態資源(JS/CSS/HTML)常包含相對路徑(如 static/mapi.css),部署到 CDN 或不同域名下需批次替換為絕對路徑(如 https://cdn.example.com/static/mapi.css)。本文提供一個 PHP 工具類,配合 Windows BAT 腳本,實現一鍵批次替換與目錄複製。

一、 核心 PHP 腳本:replace_paths.php

<?php
/**
 * 批次替換檔案內容中的佔位符,並複製目錄結構
 * 用法:php replace_paths.php
 */
class FileUtil {
    /** 需替換的正則模式陣列 */
    public static $patterns = [
        '/#BASE_URL#/'
    ];

    /** 對應的替換值 */
    public static $replacements = [
        'https://api.map.baidu.com/lbsapi/cloud/'
        // 'https://dev.example.com/static/'
    ];

    /**
     * 建立目錄(遞迴)
     */
    public static function createDir($path) {
        $path = str_replace('\\', '/', $path);
        $dir = '';
        foreach (explode('/', $path) as $part) {
            $dir .= $part . '/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
        }
    }

    /**
     * 刪除檔案
     */
    public static function unlinkFile($path) {
        return file_exists($path) ? unlink($path) : false;
    }

    /**
     * 複製檔案(含內容替換)
     * @param string $src 源檔案
     * @param string $dst 目標檔案
     * @param bool $overwrite 是否覆蓋
     */
    public static function copyFile($src, $dst, $overwrite = false) {
        if (!file_exists($src)) return false;
        if (file_exists($dst) && !$overwrite) return false;
        if (file_exists($dst) && $overwrite) self::unlinkFile($dst);

        self::createDir(dirname($dst));
        copy($src, $dst);

        // 僅對 JS/HTML/CSS 做內容替換
        if (preg_match('/\.(js|html?|css)$/i', $dst)) {
            $content = file_get_contents($dst);
            $content = preg_replace(self::$patterns, self::$replacements, $content);
            file_put_contents($dst, $content);
        }
        return true;
    }

    /**
     * 遞迴複製目錄
     */
    public static function copyDir($srcDir, $dstDir, $overwrite = false) {
        $srcDir = rtrim(str_replace('\\', '/', $srcDir), '/') . '/';
        $dstDir = rtrim(str_replace('\\', '/', $dstDir), '/') . '/';

        if (!is_dir($srcDir)) return false;
        if (!is_dir($dstDir)) self::createDir($dstDir);

        $handle = opendir($srcDir);
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') continue;
            $srcPath = $srcDir . $file;
            $dstPath = $dstDir . $file;
            if (is_dir($srcPath)) {
                self::copyDir($srcPath, $dstPath, $overwrite);
            } else {
                self::copyFile($srcPath, $dstPath, $overwrite);
            }
        }
        closedir($handle);
        return true;
    }
}

// ===== 執行入口 =====
// 將 resource/ 目錄下所有檔案複製到 cloud/,並替換 #BASE_URL#
FileUtil::copyDir(__DIR__ . '/resource', __DIR__ . '/cloud', true);
echo "完成!\n";

二、 前端檔案中預留佔位符

在源碼(resource/ 目錄)中,將需替換的路徑寫為統一佔位符:

<!-- HTML -->
<link rel="stylesheet" href="#BASE_URL#static/mapi.css">
<script src="#BASE_URL#static/main.js"></script>

/* CSS */
@import url("#BASE_URL#static/theme.css");
background: url("#BASE_URL#images/bg.png");

三、 Windows BAT 一鍵執行腳本

在專案根目錄建立 build.bat:

@echo off
echo 正在批次替換路徑並複製檔案...
php replace_paths.php
echo 完成!按任意鍵結束...
pause

雙擊 build.bat 即可自動:

  1. 讀取 resource/ 所有檔案
  2. 將 #BASE_URL# 替換為 PHP 中設定的絕對路徑
  3. 輸出到 cloud/ 目錄,保持原有結構

四、 進階:多環境切換

修改 PHP 陣列即可切換部署目標:

// 開發環境
public static $replacements = ['https://dev.example.com/static/'];

// 測試環境
public static $replacements = ['https://test-cdn.example.com/'];

// 正式環境
public static $replacements = ['https://cdn.example.com/'];

或透過 BAT 傳參數:

@echo off
set ENV=%1
if "%ENV%"=="" set ENV=prod
php replace_paths.php %ENV%

PHP 中讀取 $argv[1] 決定使用哪組替換值。

五、 Linux/Mac 替代方案

Shell 腳本同理,甚至可用 sed 單行指令:

#!/bin/bash
# 將 resource/ 複製到 cloud/ 並替換
cp -r resource/ cloud/
find cloud/ -type f \( -name "*.js" -o -name "*.html" -o -name "*.htm" -o -name "*.css" \) \
  -exec sed -i 's|#BASE_URL#|https://cdn.example.com/|g' {} +

結語

此方案零依賴、跨平台、邏輯清晰,適合中小型前端專案的建構部署流程。大型專案建議納入 Webpack/Vite/Rollup 等建構工具,利用 publicPath、環境變數、插件機制原生支援路徑替換與哈希快取破除。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved