2011-06-27 96 views
0

我已經test.txt文件,這樣,如何在php中替換一行?

AA=1 
BB=2 
CC=3 

現在我想找到 「BB =」 和替換它爲BB = 5,這樣,

AA=1 
BB=5 
CC=3 

如何做到這一點?

謝謝。

+1

傢伙您好,我得到了答案,$海峽=的preg_replace( '/ BB = \ d /','BB = 5',$ str);我認爲這是更好的方法,對吧? – CCC

+0

在這種情況下,您需要讀取字符串變量中的完整文件,運行preg_replace並用新字符串變量覆蓋文件。 –

+0

正確,(請參閱下面的評論:)) –

回答

2

假設你的檔案就像是INI文件的結構(即鍵=值),可以使用parse_ini_file和做這樣的事情:

<?php 

$filename = 'file.txt'; 

// Parse the file assuming it's structured as an INI file. 
// http://php.net/manual/en/function.parse-ini-file.php 
$data = parse_ini_file($filename); 

// Array of values to replace. 
$replace_with = array(
    'BB' => 5 
); 

// Open the file for writing. 
$fh = fopen($filename, 'w'); 

// Loop through the data. 
foreach ($data as $key => $value) 
{ 
    // If a value exists that should replace the current one, use it. 
    if (! empty($replace_with[$key])) 
    $value = $replace_with[$key]; 

    // Write to the file. 
    fwrite($fh, "{$key}={$value}" . PHP_EOL); 
} 

// Close the file handle. 
fclose($fh); 
+0

非常不錯+1 :)多數民衆贊成什麼時,你工作太多與框架,你忘了所有關於像parse_ini_file很酷的東西:) –

+0

偉大~~我喜歡這個想法。 – CCC

0

您可以使用梨包查找&替換文件中的文本。

欲瞭解更多信息,請閱讀

http://www.codediesel.com/php/search-replace-in-files-using-php/ 
+0

對不起,我不能,我正在使用嵌入式操作系統,PHP無梨支持。 – CCC

1

最簡單的方法(如果你是因爲上面所講的小文件),會是這樣的:

// Read the file in as an array of lines 
    $fileData = file('test.txt'); 

    $newArray = array(); 
    foreach($fileData as $line) { 
     // find the line that starts with BB= and change it to BB=5 
     if (substr($line, 0, 3) == 'BB=')) { 
     $line = 'BB=5'; 
     } 
     $newArray[] = $line; 
    } 

    // Overwrite test.txt 
    $fp = fopen('test.txt', 'w'); 
    fwrite($fp, implode("\n",$newArray)); 
    fclose($fp); 

(類似的東西)

+0

嗨Aaron Murray,thanks.it的小文件,但是大概有50行,如果我有50行需要替換,並且每次我們做循環,我認爲它會花費大量的資源。 – CCC

+0

@heefan好吧,我以爲你只是想要一個如何讀/寫的概述。你也可以使用$ fileData = file_get_contents('test.txt'),它會以字符串而不是數組的形式讀取它,然後使用正則表達式模式來搜索數據/操作數據,然後將其寫回到文件中。 –

+0

@heefan快速和骯髒的方法是讀取整個文件作爲字符串或數組,根據需要操作它,然後覆蓋文件(或寫入新文件)更新的信息。 –

3
<?php 

    $file = "data.txt"; 
    $fp = fopen($file, "r"); 
    while(!feof($fp)) { 
    $data = fgets($fp, 1024); 

    // You have the data in $data, you can write replace logic 
    Replace Logic function 
    $data will store the final value 

    // Write back the data to the same file 
    $Handle = fopen($File, 'w'); 
    fwrite($Handle, $data); 


    echo "$data <br>"; 
    } 
    fclose($fp); 

?> 

上面的代碼和平會給你從文件的數據,並幫助你將數據寫回到文件。