Ben
Ben

Reputation: 115

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 :)

Upvotes: 2

Views: 71

Answers (2)

Steve
Steve

Reputation: 20469

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!

Upvotes: 1

Saty
Saty

Reputation: 22532

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
}

Upvotes: 0

Related Questions