如何在PHP中删除文本字符串的第一行并输出其余部分?
例如:
这是文本字符串:
$t=<<<EOF
First line to be removed
All the rest
Must remain
EOF;
这是最终输出结果:
All the rest
Must remain
如果我要在Bash中处理一个文件,我可以轻松地执行以下操作:
sed -i~ 1d 目标文件
或者:
tail -n +2 源文件 > 目标文件
有任何想法吗?
preg_replace怎么样:
$text = "First line.\nSecond line.\nThird line.";
echo preg_replace('/^.+\n/', '', $text);
这样做,你就不必担心文件中没有换行符的情况。
http://codepad.org/fYZuy4LS.
(匹配所有字符),因此您将仅获取最后一行,而不是除第一行以外的所有内容。您应该使量词变得不贪婪,即:/^.+?\n/
。 - PatrikAkerstrand\n
,所以不是这种情况。 - Paulpreg_replace
并不慢,我对这里所有答案的解决方案进行了基准测试:http://codepad.org/xt9kK2E2 - Janexplode()
将文本按照换行符拆分成数组,shift()
取出第一行并删除,然后将剩余部分重新组合。
$arr = explode("\n", $t);
array_shift($arr);
echo implode("\n", $arr);
// Prints
// All the rest
// Must remain
strpos()
。echo substr($t, strpos($t, "\n") + 1);
$parts = explode("\n", $test, 2);
//$parts[0] has the first line
//$parts[1] has everything else
我尝试了所有这些方法,但对于大文件(50MB+),它们似乎都不够快。以下是我创建的解决方案。在您的情况下,您可以省略第一行的echo。
最初的回答:
$fh = fopen($local_file, 'rb');
echo "add\tfirst\tline\n"; // add your new first line.
fgets($fh); // moves the file pointer to the next line.
echo stream_get_contents($fh); // flushes the remaining file.
fclose($fh);
\n
。如果要使用不同的seperator,请在调用striplines()
函数时使用第三个参数。function striplines($str,$num,$seperator="\n"){
$arr = explode($seperator, $str);
for ($i=0;$i<$num;$i++) array_shift($arr);
return implode($seperator, $arr);
}
//Testcases to remove first two lines
// returns/prints only Third line
echo striplines("First line.\nSecond line.\nThird line.",2);
// returns/prints nothing
echo striplines("First line.\nSecond line.\n",2);
echo striplines("First line.\nSecond line.",2);
echo striplines("First line.\n",2);
echo striplines("First line.",2);
echo striplines("",2);
返回第一个换行符后面的子字符串:
$firstLineRemoved = $subject;
$firstNewlinePosition = strpos($subject, "\n");
if($firstNewlinePosition !== false)
{
$firstLineRemoved = substr($subject, firstNewlinePosition +1);
}
echo $firstLineRemoved;
编辑:与@ComFreek相同的示例,但在没有换行符的情况下进行错误检查
$pos = 0;
while ($str[$pos] !== PHP_EOL)
$str[$pos++] = '';
echo $str;
如果您不确定字符串是否始终包含多行,请使用以下内容:
if (strpos($str, PHP_EOL))
{
$pos = 0;
while ($str[$pos] !== PHP_EOL)
$str[$pos++] = '';
echo $str;
}
$n
没有被正确初始化。它必须是:$n = $count;
因此,它只比原来快了 2 倍,而不是 6 倍。 - Jan