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!


Given this input:

$str = "Once upon\nA Time\nLived a big\nDragon\nCalled Cuthbert.";

I want the output to be:

"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 returned array will contain a maximum of limit elements with the last element containing the rest of string.

This code removes the first three lines and keeps the rest

$str = explode("\n", $str, 4)[3];

Here's a way to visualise what's going on:

$str = "1\n2\n3\n4\n5\n6";
print_r(explode("\n", $str, 4));


    [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.

One thought on “Remove the first few lines from a string in PHP

  1. 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)

Leave a Reply

Your email address will not be published. Required fields are marked *