How to str_replace a txt file with newlines using PHP - 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

Related

How to replace PHP code in a file having newlinse

I got some files to change by clicking a button. To go for it, i have the old string to replace, saved in database, and also the new one.
On the click button, it executes a function that is gonna find the old string in the PHP file, then gonna replace it by the new one. (Final goal is to automate the PHP edits in a web software after an update).
My problem is that it perfectly works on short strings (without newline), but as soon as there is a newline into the file, nothing happens.
This is my actual code :
$path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];
}
$pos = strpos(file_get_contents($path), $old_code);
$file = file_get_contents($path);
$str = str_replace($old_code, $new_code, $file);
file_put_contents($path, $str);
$pos is "true" if my $old_code doesn't have any newline.
I tried to use preg_match to remove \n, but the problem is that when i'll have to push my edits on the file with file_put_contents, every newline will also disapear.
Example of non-working str_replace :
echo "ok"; echo 'hey there is some spaces before'
echo 'this is a sentence';
$menu = ['test1', 'test200'];
print_r($menu);
$url = "/link/to/test";
$div = "echo \"<div class='central_container' align='center'>\";";
Do you have any idea for resolving this ?
Thanks
if I`m not wrong str_replace() work only with single lines . Its have 2 options.
Option line replace str_replace() with preg_replace() or just use https://regex101.com/ there also have code generator after you finish you Regex

PHP remove last empty line in a textfile

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

PHP preg_replace alway's overwrite my read file

I have a TEXT file bla.txt
REGION_NAME = 'bla_2'
hello
hi
goodbye
my script##
<?php
$file = 'bla.txt';
$file_contents = file_get_contents($file);
$fh = fopen($file, "w");
$file_contents = preg_replace("/(REGION_NAME =) ('')/", "$1 'us-east-A'", "REGION_NAME = ''");
fwrite($fh, $file_contents);
fclose($fh);
?>
When I run it, It adds the correct text but then overwrites the bla.txt file
so and I loose the other words.
NOTE:### If I use str_replace works fine but once bla_2 changes then we can't use the script again...
Any Idea...?
$file_contents = str_replace('bla_2','bar',$file_contents);
If you read the code you are overwriting the initial value of $file_contents, not replacing against the data in $file_contents. What you need to do is: $file_contents = preg_replace("/(REGION_NAME =) ('')/", "$1 'us-east-A'", $file_contents);. And as a disclaimer I didn't actually run your code but you weren't passing in the correct subject for the function from what I see.
And I think what you want for regex is something along the lines of preg_replace("REGION_NAME = '(.*)'", 'us-east-A', $file_contents)

file_get_contents() skipping text between <> tag

I am trying to read a .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between <> tags.
Following is the format of my .tsv file
<id_svyx35_88c_avbfa5> <Kuldeep_Raval> rdf:type <wikicat_Delhi_Daredevils_cricketers>
Following is the code I am using
$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines = explode("\n", $content);
echo $content;
On reading it, the output is just
rdf:type
Please help in what can be the solution to read the line as it is?
Try to apply htmlspecialchars() to $content:
$filename = "access_s.tsv";
$content = htmlspecialchars(file_get_contents($filename));
//Split file into lines
$lines = explode("\n", $content);
echo $content;
Reference on php.net
The tags have always been there, the browser just does not show them. Just like with any valid HTML tag, you can see them when viewing the source code of the website.

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.

Categories