萬盛學電腦網

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

PHP 讀取文字檔並替換指定行內容

需求:讀取文字檔、修改特定行、寫回檔案。本文提供簡潔實作並說明大檔案處理注意事項。

基本實作 (小檔案適用)

<?php
$file_path = '123.txt';

// 1. 讀取整個檔案
$content = file_get_contents($file_path);
if ($content === false) {
    die("無法讀取檔案: $file_path");
}

// 2. 按換行分割成陣列
$lines = explode("\n", $content);

// 3. 替換指定行 (第 13 行,索引 12)
$target_line = 12;  // 0-based index
if (isset($lines[$target_line])) {
    $lines[$target_line] = "123 - 已修改於 " . date('Y-m-d H:i:s');
} else {
    die("行號超出範圍: 第 " . ($target_line + 1) . " 行不存在");
}

// 4. 合併回字串
$new_content = implode("\n", $lines);

// 5. 寫回檔案
if (file_put_contents($file_path, $new_content) === false) {
    die("寫入失敗,請檢查權限");
}

echo "第 " . ($target_line + 1) . " 行已更新";
?>

進階:通用替換函式

<?php
/**
 * 替換文字檔指定行
 * @param string $file_path 檔案路徑
 * @param int $line_num 行號 (1-based,人類直覺)
 * @param string $new_content 新內容
 * @param string $eol 換行符 (\n, \r\n, \r)
 * @return bool
 */
function replace_file_line($file_path, $line_num, $new_content, $eol = "\n") {
    if (!is_file($file_path) || !is_readable($file_path) || !is_writable($file_path)) {
        return false;
    }
    
    if ($line_num < 1) return false;
    
    $lines = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    // 注意: FILE_IGNORE_NEW_LINES 會移除換行符,適合純文字處理
    
    $index = $line_num - 1;
    if (!isset($lines[$index])) return false;
    
    $lines[$index] = $new_content;
    
    // 寫入時加回換行符
    return file_put_contents($file_path, implode($eol, $lines) . $eol) !== false;
}

// 使用範例
if (replace_file_line('config.txt', 5, 'debug_mode = true')) {
    echo "第 5 行已更新為 debug_mode = true";
} else {
    echo "更新失敗:檔案不存在、行號錯誤或權限不足";
}
?>

大檔案處理:逐行讀寫 (避免記憶體耗盡)

<?php
function replace_large_file_line($source, $dest, $line_num, $new_content) {
    $fp_in = fopen($source, 'r');
    $fp_out = fopen($dest, 'w');
    
    if (!$fp_in || !$fp_out) return false;
    
    $current_line = 0;
    while (($line = fgets($fp_in)) !== false) {
        $current_line++;
        if ($current_line === $line_num) {
            fwrite($fp_out, $new_content . "\n");
        } else {
            fwrite($fp_out, $line);
        }
    }
    
    fclose($fp_in);
    fclose($fp_out);
    
    // 原子性替換
    return rename($dest, $source);
}

// 使用
replace_large_file_line('huge.log', 'huge.log.tmp', 100000, 'NEW LINE CONTENT');
?>

關鍵函式對照

函式用途特性
file_get_contents一次讀全檔簡單、小檔案適用
file()讀成陣列自動分行、可忽略換行符
fopen/fgets逐行讀取記憶體效率高、大檔案必備
file_put_contents一次寫入原子性 (Linux)、支援 LOCK_EX
fwrite流式寫入大檔案、需自行管理

注意事項

  • 編碼一致性:讀寫編碼必須一致 (UTF-8 推薦)
  • 檔案鎖定:併發環境用 flock() 或寫暫存檔再 rename
  • 備份機制:重要檔案修改前先備份
  • 行尾差異:跨平台處理時統一轉換
copyright © 萬盛學電腦網 all rights reserved