Home >Backend Development >PHP Tutorial >How to Replace Lines in Text Files Based on Word Matching in PHP?

How to Replace Lines in Text Files Based on Word Matching in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 10:02:12246browse

How to Replace Lines in Text Files Based on Word Matching in PHP?

Replacing Lines in Text Files Based on Word Matching Using PHP

In scenarios where the line number is unknown, replacing specific lines based on word matching can be a challenging task. Fortunately, PHP offers several effective approaches to tackle this situation:

For Smaller Files (Fit into Memory):

  1. Read the entire file into an array of lines using file('myfile').
  2. Create a function to replace the desired line, such as replace_a_line($data):

    • Check if the line contains the target word using stristr($data, 'certain word').
    • If found, return the replacement line as a string.
    • Otherwise, return the original line.
  3. Apply the replacement function to each line in the array using array_map('replace_a_line', $data).
  4. Write the modified array back to the file using file_put_contents('myfile', $data).
  5. Enhance the method by using lambda functions to simplify the array_map:

    • $data = array_map(function($data) { ... }, $data);

For Larger Files (Memory Intensive):

  1. Open the file for reading and writing using fopen('myfile', 'r') and fopen('myfile.tmp', 'w') respectively.
  2. Set a flag to indicate if a replacement is made ($replaced).
  3. Read each line in the input file using fgets($reading).
  4. Check for the presence of the target word using stristr($line, 'certain word').
  5. If found, replace the line with the modified version.
  6. Write the updated line to the output file using fputs($writing, $line).
  7. Close the file handles after processing.
  8. Replace the original file with the modified one only if a replacement was made (rename('myfile.tmp', 'myfile')) or delete the temporary file if no replacement was needed (unlink('myfile.tmp')).

The above is the detailed content of How to Replace Lines in Text Files Based on Word Matching in 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