Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: delete the first line of a text and return the rest

Tags:

string

php

What's the best way to remove the very first line of a text string and then echo the rest in PHP?

For example.

This is the text string:

$t=<<<EOF
First line to be removed
All the rest
Must remain
EOF;

This is the final output:

All the rest
Must remain

If I was working with a file in Bash I could do easily the next:

sed -i~ 1d target-file

Or:

tail -n +2 source-file > target-file

Any ideas?

like image 707
Roger Avatar asked Sep 04 '25 16:09

Roger


1 Answers

In alternative to the other answers with either explode & implode or regular expressions, you can also use strpos() and substr():

function stripFirstLine($text) {        
  return substr($text, strpos($text, "\n") + 1);
}
echo stripFirstLine("First line.\nSecond line.\nThird line.");        

Live example: http://codepad.org/IoonHXE7

like image 191
ComFreek Avatar answered Sep 07 '25 05:09

ComFreek