Как заменить одну строку в php? - PullRequest
0 голосов
/ 27 июня 2011

У меня есть файл test.txt, например,

AA=1
BB=2
CC=3

Теперь я хочу найти «BB =» и заменить его на BB = 5, например,

AA=1
BB=5
CC=3

Как мне это сделать?

Спасибо.

Ответы [ 4 ]

3 голосов
/ 27 июня 2011
<?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);

?>

Приведенный выше кодекс предоставит вам данные из файла и поможет записать данные обратно в файл.

2 голосов
/ 27 июня 2011

Предполагая, что ваш файл структурирован как 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);
1 голос
/ 27 июня 2011

Самый простой способ (если вы говорите о маленьком файле, как указано выше), будет выглядеть примерно так:

    // 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 голосов
/ 27 июня 2011

Вы можете использовать пакет Pear для поиска и замены текста в файле.

Для получения дополнительной информации читайте

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