PHP:删除文本的第一行并返回其余部分

2022-08-30 16:15:32

删除文本字符串的第一行,然后在PHP中回显其余部分的最佳方法是什么?

例如。

这是文本字符串:

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

这是最终输出:

All the rest
Must remain

如果我在Bash中处理一个文件,我可以很容易地做下一个:

sed -i~ 1d target-file

艺术

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

有什么想法吗?


答案 1

除了使用 & 或正则表达式的其他答案之外,您还可以使用 strpos()substr()explodeimplode

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

实际示例:http://codepad.org/IoonHXE7


答案 2

preg_replace怎么样:

$text = "First line.\nSecond line.\nThird line.";
echo preg_replace('/^.+\n/', '', $text);

这样,您就不必担心文件中没有换行符的情况。
http://codepad.org/fYZuy4LS


推荐