How can PHP code be optimized to efficiently handle file searches and replacements?

When handling file searches and replacements in PHP, it is important to optimize the code to efficiently process large files without causing memory issues. One way to achieve this is by using functions like `fopen`, `fread`, and `fwrite` to read and write files in smaller chunks rather than loading the entire file into memory at once. Additionally, using regular expressions with functions like `preg_replace` can help efficiently search and replace content within files.

<?php
$file = 'example.txt';
$search = 'old_string';
$replace = 'new_string';

$handle = fopen($file, 'r+');
$buffer = '';
while (!feof($handle)) {
    $buffer = fread($handle, 8192);
    $buffer = preg_replace('/\b' . preg_quote($search, '/') . '\b/', $replace, $buffer);
    fseek($handle, -strlen($buffer), SEEK_CUR);
    fwrite($handle, $buffer);
}
fclose($handle);
?>