What are some strategies for efficiently manipulating and modifying text data within a file using PHP?

When manipulating and modifying text data within a file using PHP, one efficient strategy is to read the file line by line, apply the necessary modifications, and then write the modified content back to the file. This approach helps avoid memory issues when dealing with large files and allows for easy manipulation of text data.

$file = 'example.txt';
$tempFile = 'temp.txt';

$handle = fopen($file, 'r');
$tempHandle = fopen($tempFile, 'w');

while (($line = fgets($handle)) !== false) {
    // Modify the text data as needed
    $modifiedLine = str_replace('old_text', 'new_text', $line);
    
    fwrite($tempHandle, $modifiedLine);
}

fclose($handle);
fclose($tempHandle);

// Replace the original file with the modified content
rename($tempFile, $file);