简体   繁体   English

在每行的末尾添加一个字符串,但不是在第一行

[英]Adding a string to the end of each line but not the first line

I am trying to add a string to the end of eachline.我正在尝试在每行的末尾添加一个字符串。 So far this works.到目前为止,这是有效的。 However I dont want the string to be added to the end of the first line.但是我不希望将字符串添加到第一行的末尾。 How can I do this?我怎样才能做到这一点?

So far i have got:到目前为止,我有:

<?php

$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
    $newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);

$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);

?>

I have also tried to loop it by doing this:我也尝试通过这样做来循环它:

<?php

$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
    if ($x > 0) {
        $newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
    }
    $x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);

$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);

?>

So the end result would look like:所以最终的结果应该是这样的:

firstonestring secondonestring thirdonestring第一个字符串 第二个字符串 第三个字符串

and so on.等等。

I hope you can help me!我希望你可以帮助我!

Ben :)本 :)

Just add a counter to your loop:只需在循环中添加一个计数器:

$counter = 0;
while(!feof($baseFile)) {
    $line = fgets($baseFile)
    if($counter++ > 0){
        $newFile.= str_replace(PHP_EOL, $EOLString, $line);
    }else{
        $newFile.= $line . "\n";
    }
}

Also, you seem to be writting the new file, only to reopen it and append more data.此外,您似乎正在编写新文件,只是为了重新打开它并附加更多数据。 There is no need to do that, just append to the contents before you write it the 1st time:没有必要这样做,只需在第一次写入之前附加到内容:

fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);

//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);

Alternativly, you can just read in the whole file, split into lines, and rejoin:或者,您可以读取整个文件,分成几行,然后重新加入:

$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!

By using a flag通过使用标志

$first = TRUE;//set true first time
while (!feof($baseFile)) {
    $line = fgets($baseFile);
    if (!$first) {// only enter for false
        $newFile.= str_replace(PHP_EOL, $EOLString, $line);
    }
    $first = FALSE;// set false except first
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM