In PHP, how can I capture the entire line containing a found word in a file into a string variable?

Solution 1:

You can use a line-based regular expression to match the word and capture the entire line that contains it. For example:


preg_match('/^.*WORD.*$/m', $filecontents, $matches);

This way, $matches will contain the full line(s) where WORD was found.

🔹 Notes:

The ^ and $ anchors match the start and end of a line.

The m (multiline) modifier makes ^ and $ apply to each line within the string, not just the beginning and end of the whole string.

If you expect multiple matches, use preg_match_all() instead of preg_match().


preg_match_all('/^.*WORD.*$/m', $filecontents, $matches);

Then $matches[0] will contain all matching lines.

Solution 2:

You can efficiently scan the file line by line using fgets(), which avoids loading the whole file into memory.


$path = "/path/to/wordlist.txt";
$word = "Word";

$handle = fopen($path, 'r');
$currentline = 1;   // Track line numbers if needed
$lines = [];

while (!feof($handle)) {
    $line = fgets($handle);
    
    // Use !== false to correctly detect matches at position 0
    if (strpos($line, $word) !== false) {
        $lines[$currentline] = $line;
    }
    
    $currentline++;
}

fclose($handle);

🔹 Notes:

Using strpos($line, $word) !== false is important — otherwise matches at the start of the line (index 0) would be missed.

$lines will store all matching lines, keyed by their line number.

If you only need the first match, replace the array assignment with a single variable and add a break after storing it.

✅ Advantages:

Works efficiently even on very large files (unlike file() or preg_split, which load the entire file into memory).