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 PHP$str = "Once upon\nA Time\nLived a big\nDragon\nCalled Cuthbert.";

I want the output to be:

PHP 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 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

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

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

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

Outputs:

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

Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

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)

    Reply

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">