PHP remove last empty line in a textfile - php

I have a problem with a textfile.
I have a textfile with an empty line (always the last line is empty).
I need to remove this line. I tried several ways. Here is my current way to delete empty lines:
function RemoveEmptyLines($filename)
{
$myfile = fopen($filename, "r") or die("Unable to open file!");
$Content = fread($myfile,filesize($filename));
fclose($myfile);
$NewContent = preg_replace('/^\s+/m', '', $Content);
$myfile2 = fopen('new.txt', "w") or die("Unable to open file!");
fwrite($myfile2, $NewContent);
fclose($myfile2);
echo "removed";
}
This deletes all the empty lines within the textfile, but not the last empty line.
If the content is:
1 \n 2 \n \n 3
It deletes the empty line.
If it is:
1 \n 2 \n 3 \n \n
It doesn´t..
Any solutions?
The problem is, that the file is dynamic, so I can´t just delete the last line, because it´s not always empty..

Get the contents, trim the end and put the contents:
file_put_contents($filename, rtrim(file_get_contents($filename));
Or, for your existing code, you don't want m (PCRE_MULTILINE) and you want to match the end of the string $. I think this pattern will work:
/\s+$/
Both solutions will removes spaces as well. If you don't want that:
/[\n\r]+$/
If you really want to delete ALL empty lines then you can read the file into an array, ignoring empty lines and put the contents back:
file_put_contents($filename, file($filename, FILE_SKIP_EMPTY_LINES));
However, if you are creating this file you might want to look at that code and not add the newline in the first place.

Have you tried rtrim? Might be what you need:
rtrim($NewContent);

Related

How to str_replace a txt file with newlines using PHP

I have a text file with the following 2 lines
woof
woof99
I then have this code where it's supposed to take the username, example woof and take it out and replace it with nothing.
$file = fopen("../UsersProfile/".$MyUsername."/otherfiles/Following.txt","a") or die("Unable to open file");
$content = file_get_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt");
$newcontent = str_replace($Username."\n", '', "$content");
file_put_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt", "$newcontent");
fclose($file);
the text file will then look like this with one line now.
woof99
the issue that I am having is that it isn't working for some reason. I believe it worked before but for some reason now it isn't. Is there an easier way to do this?
Thanks!
Edit: I found out what I needed to do I need to do \r\n
$newcontent = str_replace($Username."\n", '', $content);
Just turn this "$content" to this $content :D

Why does it add the text at the beginning of next line, and not the end of the right one?

Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...

Add comma to the end of every line in a text file PHP

I started learning PHP this week and need to add a comma to the end of every line in a text file. I don't really know where to start. What would I do after I load the file? I can't find any tutorial saying how to write to the end of every line only the beginning of the file or end?? Is it possible to specify the end of a every line?
What I have so far:
fopen("file.txt",a)
????
I'm using "a" because I want to preserve the data.
This should work for you:
(Here I just get all file lines with file(). Then I go through each line with array_map() and concatenate a comma at the end. After this I save the file with the new content with file_put_contents())
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map(function($v){return $v . "," . PHP_EOL;}, $lines);
file_put_contents("test.txt", $lines);
?>
Example file:
a
a
a
after the script:
a,
a,
a,
EDIT:
If you don't want to add a comma to an empty line just add a condition to check if the line is empty or not like this:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map(function($v){return $v . (empty($v)?"":",") . PHP_EOL;}, $lines);
file_put_contents("test.txt", $lines);
?>
Do you want to replace all the EOL with some specific character ?
$EOLChar=",";
$myFile = fopen("file.txt", "r") ;
$newFile="";
while(!feof($myFile)) {
$newFile.= str_replace(PHP_EOL, $EOLChar, fgets($myFile));
}
fclose($myFile);
file_put_contents("file.txt", $newFile);

Starting a newline for CSV in foreach loop?

I need to start a new line every time it loops through and adds to the CSV document that is getting generated.
Code:
if(is_array($results_top_pages->getRows())){
$name = rand();
$myfile = fopen("bin/".$name.".csv", "w") or die("Unable to open file!");
foreach($results_top_pages->getRows() as $top_page){
$txt = array($top_page[0]. ",".$top_page[1]);
fputcsv($myfile, $txt);
}
fclose($myfile);
}
I have tried the following:
- array($top_page[0]. ",".$top_page[1]. "\n");
- array($top_page[0]. ",".$top_page[1]. "\r\n");
- array($top_page[0]. ",".$top_page[1]. "<br>");
As well as all the above with '' instead of ""
Still no luck. Everything that is generated is all one line when opened in excel.
Thanks in advance.
It should detect the line endings. From putcsv doc:
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Hope this helps.
Lose the quoted comma in $txt = array($top_page[0]. ",".$top_page[1]); Do this instead:
$txt = array($top_page[0], $top_page[1]);
fputcsv automatically puts line endings. What you're actually doing in your example is sending a single element array.

In PHP when using fgets() to read from file how to exclude "brake row"

I'm writing simple function witch will read data from myfile.txt with fgets().
Content of file is something like:
1
2
3
4
Function to get first value (1):
$f = fopen ("myfile.txt", "r");
$mystring = fgets ($f);
Now, when I use $mystring to write in file like:
$f1 = fopen ("myfile2.txt", "w");
fwrite($f1, 'text' . $mystrin . 'more text');
text 'more text' goes to new row.
I want to have it in in same row with other text.
When reading a file using fgets() it will include the newline at the end. You only need to remove it.
$mystring = trim ($mystring);
This will remove any leading and trailing whitespaces.
$mystring = rtrim ($mystring, PHP_EOL);
Will remove any trailing newlines.

Categories