Problem: I have a multiline
string – not a file – and I want to remove the first few lines from it and keep the rest. I found this surprisingly unintuitive. So these are notes in case I want to do it again. Feel free to suggest a better way!
Given this input:
$str = "Once upon\nA Time\nLived a big\nDragon\nCalled Cuthbert.";
I want the output to be:
That is, remove the first X lines in a string.
explode() converts a
string into an
array based on a delimiter character.
limitis set and positive, the returned
arraywill contain a maximum of
limitelements with the last element containing the rest of
This code removes the first three lines and keeps the rest
$str = explode("\n", $str, 4);
Here’s a way to visualise what’s going on:
$str = "1\n2\n3\n4\n5\n6"; print_r(explode("\n", $str, 4));
Array (  => 1  => 2  => 3  => 4\n5\n6 )
What not to do…
- Loop through the string, counting the instances of
\nand then substringing based on that position.
- Write the string to a file and then read it line by line.