如何在PHP中替换一行?

时间:2011-06-27 03:59:14

标签: php file design-patterns

我有test.txt文件,像这样,

AA=1
BB=2
CC=3

现在我想找到“BB =”并将其替换为BB = 5,就像这样,

AA=1
BB=5
CC=3

我该怎么做?

感谢。

4 个答案:

答案 0 :(得分: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);

?>

上面的代码安静将为您提供文件中的数据,并帮助您将数据写回文件。

答案 1 :(得分:2)

假设您的文件结构类似于INI文件(即key = value),您可以使用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);

答案 2 :(得分: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);

(类似的东西)

答案 3 :(得分:0)

您可以使用Pear包查找&amp;替换文件中的文本。

欲了解更多信息,请阅读

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