萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 批量將相對路徑替換為絕對路徑:自動化構建腳本實戰

應用場景

前端項目構建發布時,需將 HTML/CSS/JS 中的相對資源路徑(如 static/mapi.css)批量替換為 CDN 絕對路徑(如 https://cdn.example.com/static/mapi.css)。手動替換效率低且易出錯,編寫 PHP 腳本實現自動化遞歸掃描替換。

核心類:FileUtil

<?php
/**
 * 文件操作工具類:複製目錄、複製文件、創建目錄、刪除文件
 * 內建變量替換功能:針對 .js/.html/.css/.htm 文件進行正則替換
 */
class FileUtil {
    // 全局替換規則
    public static $patterns = [
        '/#BASE_URL#/'  // 源碼中統一使用 #BASE_URL# 作為佔位符
    ];
    public static $replacements = [
        'https://api.map.baidu.com/lbsapi/cloud/'  // 目標絕對路徑
    ];

    /** 創建多級目錄 */
    public static function createDir(string $path): void {
        $path = str_replace('\\', '/', $path);
        $dir = '';
        foreach (explode('/', $path) as $segment) {
            $dir .= $segment . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
        }
    }

    /** 刪除文件 */
    public static function unlinkFile(string $path): bool {
        if (file_exists($path)) {
            return unlink($path);
        }
        return false;
    }

    /** 遞歸複製目錄 */
    public static function copyDir(string $srcDir, string $dstDir, bool $overwrite = false): bool {
        $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;
    }

    /** 複製單個文件,支持內容替換 */
    public static function copyFile(string $srcPath, string $dstPath, bool $overwrite = false): bool {
        if (!file_exists($srcPath)) return false;
        if (file_exists($dstPath) && !$overwrite) return false;
        if (file_exists($dstPath) && $overwrite) self::unlinkFile($dstPath);

        self::createDir(dirname($dstPath));
        copy($srcPath, $dstPath);

        // 僅對文本類文件進行變量替換
        if (preg_match('/\.(js|html?|css|htm|json|xml|svg|txt|md)$/i', $dstPath)) {
            $content = file_get_contents($dstPath);
            $content = preg_replace(self::$patterns, self::$replacements, $content);
            file_put_contents($dstPath, $content);
        }
        return true;
    }
}

// ===== 執行入口 =====
// 將 resource/ 目錄下所有文件複製到 cloud/ 並替換變量
FileUtil::copyDir(__DIR__ . '/resource', __DIR__ . '/cloud', true);
echo "構建完成:resource/ → cloud/ (變量已替換)\n";

批處理啟動腳本 (build.bat)

@echo off
chcp 65001 >nul
echo 正在構建靜態資源...
php release.php
if errorlevel 1 (
    echo 構建失敗!
    pause
    exit /b 1
)
echo 構建成功!
pause

使用說明

  1. 項目結構:
project/
├── resource/          # 源碼目錄(含 #BASE_URL# 佔位符)
│   ├── index.html
│   ├── static/
│   │   ├── style.css
│   │   └── app.js
│   └── images/
├── cloud/             # 構建輸出目錄(自動生成)
├── release.php        # PHP 構建腳本
└── build.bat          # 雙擊運行
  1. 源碼中統一使用佔位符:<link href="#BASE_URL#static/style.css">、background: url(#BASE_URL#images/bg.png)。
  2. 雙擊 build.bat,自動生成 cloud/ 目錄,所有佔位符已替換為絕對 CDN 地址。
  3. 部署時直接上傳 cloud/ 目錄內容至 CDN/靜態服務器。

擴展:多環境配置

<?php
// release.php 增加環境參數支持
$env = $argv[1] ?? 'prod'; // php release.php test|prod
$configs = [
    'dev'   => 'https://dev.local/lbsapi/cloud/',
    'test'  => 'https://test.example.com/lbsapi/cloud/',
    'prod'  => 'https://api.map.baidu.com/lbsapi/cloud/',
];
FileUtil::$replacements = [$configs[$env] ?: $configs['prod']];
FileUtil::copyDir(__DIR__ . '/resource', __DIR__ . '/cloud_' . $env, true);

進階替換:多變量、正則捕獲組

public static $patterns = [
    '/#BASE_URL#/',
    '/#API_VERSION#/',
    '/#TIMESTAMP#/',
];
public static $replacements = [
    'https://cdn.example.com/v2/',
    'v2.1.0',
    date('YmdHis'),
];

// 或使用回調函數動態替換
$content = preg_replace_callback('/#\{(\w+)\}#/', function($m) use ($vars) {
    return $vars[$m[1]] ?? $m[0];
}, $content);
copyright © 萬盛學電腦網 all rights reserved