Terence Eden. He has a beard and is smiling.
Theme Switcher:

Remove the first few lines from a string in PHP

· 1 comment · 250 words · Viewed ~825 times


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

Share this post on…

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

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

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

To respond on your own website, write a post which contains a link to this post - then enter the URl of your page here. Learn more about WebMentions.