How can I loop through each line of a string in PHP?

Solution 1:

A much faster and more memory-efficient alternative to preg_split is to use strtok.


$separator = "\r\n";
$line = strtok($subject, $separator);

while ($line !== false) {
    // Process each line
    $line = strtok($separator);
}

Performance comparison:
I tested this by iterating 100 times over a file containing ~17,000 lines.

preg_split → 27.7 seconds

strtok → 1.4 seconds

That’s a huge performance gain.

⚠️ Note: Although $separator is defined as “\r\n”, strtok actually treats each character in the separator string as a delimiter. Since PHP 4.1.0, it also skips empty tokens/lines.

Solution 2:

Another approach is to stream the data into an in-memory file and read it line by line with fgets().
It may look a bit more verbose, but it’s efficient and avoids loading the entire split result into memory:


$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);

while ($line = fgets($fp)) {
    // Process each $line
}

fclose($fp);

Why this works well:

php://memory provides a temporary, in-memory stream.

You write $data into it, then rewind() to reset the pointer.

fgets() reads the stream line by line, which is both memory-efficient and cleaner than splitting.