Replace a whole line where a particular word is found in a text file

Replace a whole line where a particular word is found in a text file

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Replacing Lines by Content, Not Position

Finding a specific string inside a file and swapping out an entire line based on that match is a common task in text processing. The core challenge here is that you don't know the line number beforehand. If you rely solely on reading the file sequentially into memory, you risk loading a massive dataset entirely before you can perform any edits, which defeats the purpose of efficient text manipulation.

To handle this efficiently without knowing the line index, you need to process the file as a stream or iterate through it line by line. This approach allows you to maintain state regarding what you have read while keeping memory usage constant regardless of file size. The most straightforward method in PHP involves opening the file for reading and writing simultaneously or using temporary files to ensure data integrity during the swap operation.

Stream Processing with fgetcsv and Regex

If your goal is simple text replacement, regular expressions are often the cleanest tool. You can open the input file for reading and an output file (or a temporary file) for writing. As you iterate through each line using fgets(), you check if the line contains your target keyword. If it does, you apply the substitution logic; otherwise, you pass the line through unchanged.

Here is a practical example demonstrating how to replace a whole line containing the word "deprecated" with a new comment block:

$inputFile = 'config.php';
$outputFile = '/tmp/config_updated.php';
$keyword = 'deprecated';
$replacementLine = '// [REMOVED] This line contained deprecated logic.';

$handle = fopen($inputFile, 'r');
$output = fopen($outputFile, 'w');

if ($handle && $output) {
    while (($line = fgets($handle)) !== false) {
        if (strpos($line, $keyword) !== false) {
            // Replace the entire line if the keyword is found
            fwrite($output, $replacementLine . PHP_EOL);
        } else {
            // Pass through unchanged lines exactly as they are
            fwrite($output, $line);
        }
    }

    fclose($handle);
    fclose($output);
}

This pattern is robust because it treats every line as a distinct unit. It doesn't assume anything about the structure of the remaining file content. However, you must remember that fgets() includes the newline character (\n or \r\n). If your replacement logic requires stripping these characters to avoid double newlines in the output, you should handle them explicitly before writing.

Using Regular Expressions for Precision

While strpos() works well for simple existence checks, regular expressions offer more control if you need to validate the line structure before replacing it. For instance, you might only want to replace a line if the keyword appears at the very beginning of the line, or if it is surrounded by specific delimiters.

You can leverage preg_replace() combined with file iteration to achieve this without needing to calculate line numbers manually. The regex pattern can anchor the search to the start or end of the line using ^ and $.

$pattern = '/^\s*\S+\s+' . preg_quote($keyword, '/') . '\s*$/', // Matches lines starting with non-whitespace containing keyword
$replacement = '// Line containing ' . $keyword . ' has been removed.';

$handle = fopen($inputFile, 'r');
$output = fopen($outputFile, 'w');

if ($handle && $output) {
    while (($line = fgets($handle)) !== false) {
        // Use preg_replace to swap the line if it matches the pattern
        $newLine = preg_replace($pattern, $replacement, $line);
        
        // Only write if a replacement occurred or if we are just echoing unchanged lines
        if ($newLine !== $line) {
            fwrite($output, $newLine . PHP_EOL);
        } else {
            fwrite($output, $line);
        }
    }
}

This approach ensures that you only modify lines that strictly match your criteria. It prevents accidental corruption of adjacent lines or partial matches within a larger block of text. Always use preg_quote() if the keyword itself contains regex special characters like dots or asterisks, as failing to do so can lead to unexpected behavior in production environments.

Safety Considerations and Best Practices

When performing in-place edits on files that are part of an active application, direct overwriting can be risky. If the process is interrupted by a power failure or a crash after writing partial data, the original file becomes corrupted. The safest strategy is always to write changes to a temporary file first, then rename it once the operation completes successfully. This atomic swap ensures that either the old version exists or the new version does, never a hybrid state.

Additionally, consider the encoding of your files. If you are dealing with UTF-8 strings containing multi-byte characters (like accented letters or emojis), ensure that fgets() and fwrite() handle them correctly by setting the appropriate locale or using mb_convert_encoding if necessary. While standard PHP functions usually handle UTF-8 transparently, binary file handling requires extra caution to prevent byte-order mark corruption.

For complex scenarios where you need to manage multiple conditions or integrate this logic into a larger workflow within a Laravel application, consider leveraging existing utility packages. Resources like https://laravelcompany.com often provide insights into best practices for file system operations within the ecosystem, though standard PHP functions remain the most portable and dependency-free solution for text manipulation tasks.

Our network