Remove the first few lines from a string in PHP
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!
Example
Given this input:
PHP$str = "Once upon\nA Time\nLived a big\nDragon\nCalled Cuthbert.";
I want the output to be:
PHP"Dragon\nCalled Cuthbert."
That is, remove the first X lines in a string.
Exploding kittens
Using explode()
converts a string
into an array
based on a delimiter character.
If
limit
is set and positive, the returnedarray
will contain a maximum oflimit
elements with the last element containing the rest ofstring
.
This code removes the first three lines and keeps the rest
PHP$str = explode("\n", $str, 4)[3];
Here's a way to visualise what's going on:
PHP$str = "1\n2\n3\n4\n5\n6";
print_r(explode("\n", $str, 4));
Outputs:
PHPArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4\n5\n6
)
What not to do...
- Loop through the string, counting the instances of
\n
and then substringing based on that position. - Write the string to a file and then read it line by line.
Duggie says:
Here's how to do it with a regular expression (substitution) which will replace the first 3 matches with empty string and leave the rest of the string untouched: preg_replace('/.*?\n/', '', $str, 3)