Home >Backend Development >PHP Tutorial >How to Replace a Specific Line in a Text File Using PHP?

How to Replace a Specific Line in a Text File Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 06:10:02603browse

How to Replace a Specific Line in a Text File Using PHP?

Replacing a Specific Line in a Text File Using PHP

Need to edit a text file and zero in on a specific line containing a particular word? Let's dive into the world of PHP and explore two techniques to replace that line with ease.

Method 1: In-Memory Line Replacement

For smaller files that can be comfortably held in memory, you can use the following approach:

$data = file('myfile'); // Reads an array of lines

function replace_a_line($data) {
  if (stristr($data, 'certain word')) {
    return "replacement line!\n";
  }
  return $data;
}

$data = array_map('replace_a_line', $data);
file_put_contents('myfile', $data);

Method 2: Less Memory Intensive Line Replacement

For larger files, try this more memory-conserving method:

$reading = fopen('myfile', 'r');
$writing = fopen('myfile.tmp', 'w');

$replaced = false;

while (!feof($reading)) {
  $line = fgets($reading);
  if (stristr($line,'certain word')) {
    $line = "replacement line!\n";
    $replaced = true;
  }
  fputs($writing, $line);
}
fclose($reading); fclose($writing);

// Don't overwrite if nothing replaced
if ($replaced) {
  rename('myfile.tmp', 'myfile');
} else {
  unlink('myfile.tmp');
}

There you have it! The choice of approach depends on the size of your file and your memory constraints. Remember, for large files, the second method is your ally, while the first method excels with smaller files.

The above is the detailed content of How to Replace a Specific Line in a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn