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.