Home > Backend Development > PHP Tutorial > How Can I Replace Specific Lines in a Text File with PHP?

How Can I Replace Specific Lines in a Text File with PHP?

Linda Hamilton
Release: 2024-11-13 02:42:02
Original
1080 people have browsed it

How Can I Replace Specific Lines in a Text File with PHP?

Replacing Specific Lines in a Text File with PHP

Within a text file, selectively replacing lines based on the presence of a particular word is a common requirement. In this regard, PHP provides several approaches to accomplish this task.

Using Array Functions for Smaller Files (Fit into Memory)

For text files that fit into memory, the following approach can be employed:

$data = file('myfile'); // Array of lines
function replace_a_line($data) {
    return (stristr($data, 'certain word')) ? "replacement line!\n" : $data;
}
$data = array_map('replace_a_line', $data);
file_put_contents('myfile', $data);
Copy after login

Lambda functions in PHP versions > 5.3.0 allow for a concise version:

$data = array_map(function($data) {
    return (stristr($data, 'certain word')) ? "replacement line\n" : $data;
}, $data);
Copy after login

For Larger Files (Memory-Intensive)

With larger files, the below approach iterates line-by-line without loading the entire file into memory:

$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);
if ($replaced) rename('myfile.tmp', 'myfile');
else unlink('myfile.tmp');
Copy after login

By implementing these techniques, you can effectively replace specific lines in a text file based on a word match.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template