Remove Line from String within txt file - php

Currently I have a code, which displays data from a txt file, and randomizes it after converting it into an array.
$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);
I am trying to make it so that, after this random value is displayed.
$search = $array[$rand_keys[0]];
We're able to store this into another txt file such as completed.txt and remove the randomized segment from our previous txt file. Here's the approach I tried, and surely didn't work out with.
$a = 'test.txt';
$b = file_get_contents('test.txt');
$c = str_replace($search, '', $b);
file_put_contents($a, $c);
Then to restore into a secondary file, I was messing with something like this.
$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $search;
}
}
file_put_contents('completed.txt', $result);
This actually appears to work to some extent, however when I look at the file completed.txt all of the contents are EXACTLY the same, and there's a bunch of blank spaces being left behind within test.txt

There are some better ways of doing it (IMHO), but at the moment you are just removing the actual line without the new line character. You may also find it will replace other lines as it just replaces the text without any idea of content.
But you will probably fix your code with the addition of replacing the new line...
$c = str_replace($search."\n", '', $b);
An alternative way of doing it is...
$fileName = 'test.txt';
$fileComplete = "completed.csv";
// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));
// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);

Related

Php split text by line and get specific element

I have a big text file, split by new lines and on every line elements split by ';', like this:
1;1;20;3.6;0%;70%;25%;0%;5%;
1;2;80;4;45%;20%;20%;15%;0%;
1;3;80;4;40%;35%;5%;20%;0%;
1;4;20;3.6;15%;40%;38%;5%;2%;
1;5;20;3.6;30%;18%;33%;20%;0%;
1;6;80;4;27%;47%;23%;3%;0%;
What I would like to do is with PHP is to read the file correctly and access a specific element in any row, for example on row 2, element 3 (maybe, [1][2], if considered as indexes) and print it.
<?php
//split by new line
$text = fopen("public/data/data1.txt", "r");
if ($text) {
while (($lines = fgets($text)) !== false) {
//split by ;
$line = explode(';', $lines);
//access a specific element
}
fclose($text);
} else {
// error opening the file.
}
?>
Does somebody know how I could access this elements?
You can explode the string twice.
First on lines, then on ;.
$arr = explode(PHP_EOL, $str);
Foreach($arr as &$line){
$line = explode(";", $line);
}
https://3v4l.org/5fbvZ
Then echo $arr[1][2]; will work as you wanted

Make Php string without break lines

i need to generate random sentences from dictionary. In dictionary is every word at one line, firstly i load this dictionary to array and after it i have a for cycle and randomly pickup some data, but if i wrote it, so it is at one line in browser, but in source code is every word at another line. Then I need to create a set of XML files from search engine and this new lines are indexed as /n/r and in XML source code it has got a symbol 
 So my question is how i can make a sentence which will be at one line in source code too. Thanks.
Here is piece of my code i donĀ“t have here randomly loading data, i only made it for illustration in for cycle.
$file = fopen("test.txt", "r");
$data = array();
while (($buffer = fgets($file)) !== false) {
$data[] = $buffer;
}
$sentence = '';
for ($i=0;$i<10;$i++){
$sentence = $sentence . $data[$i];
}
Use trim function to filter new line characters.
In your code use:
$data[] = trim($buffer);

remove everything after first space on each line of this text file

In PHP, how can one edit a text file and save it so that everything after the first space is removed?
In other words, so that each line only has its first word?
For example, if the text file looked like this:
Adi NNP
Adia NNP
Adios NNP FW
Adios-Direct NNP
Adios-On NNP
Adios-Rena NNP
Adios-Trustful NNP
Adirondack NNP
Adirondacks NNPS
Adjoining VBG
Adjournment NN
after executing the script, the text file would look like this:
Adi
Adia
Adios
Adios-Direct
Adios-On
Adios-Rena
Adios-Trustful
Adirondack
Adirondacks
Adjoining
Adjournment
How I would approach this would be to open the file, read it in, and take each line and store it in an array. Then replace everything after the first space with nothing. And lastly, save the edited array to a new file.
Is there a better way to do it than that?
All I know how to do in the above method is everything except the last two tasks. I would do it like so:
$file = array();
$lines = file('file.txt');
foreach($lines as $line){
array_push($file, $line);
}
// now travel through $file and replace everything after first space with nothing
// travel though $file again, but write each element as a new line in a .txt file
You can use explode() to separate the line by spaces. Then you can immediately write the string back to a file, no second loop is required:
$file = array();
$lines = file('file.txt');
$new_file = fopen('new.txt', 'w+');
foreach($lines as $line){
$bits = explode(' ', $line);
fwrite($new_file, $bits[0] . PHP_EOL);
}
fclose($new_file);
You can do it in the same line: just replace array_push($file, $line) with...
$file[] = strtok($line, ' ');
It can be written even more compact with help of array_map:
$lines = array_map(function($line) {
return strtok($line, ' ');
}, file('file.txt'));
... or you can write it back immediately, as shown in #hek2mgl answer.
You can bypass arrays entirely and do this with a simple regular expression:
// Read in contents into a variable
$data = file_get_contents('input.txt');
// Drop the space and everything after on each line
$data = preg_replace('/ .*$/m', '', $data);
// Dump contents to file (change this to input.txt if you want to overwrite the file)
file_put_contents('output.txt', $data);

how to replace some part of text from the text file in php

I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).

PHP extract data from text file and write to another file

This is my first post on the internet for some assistance with coding so please bear with me!
I have been finding open code on the internet for a few years and modding it to do what I want but I seem to have come up against a wall with this one that I am sure is very simple. If you would please be able to help me it would be very much appreciated.
I have the following page:
<?php
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis)
{
foreach($inthis as $pos => $a){
}
$newarr = implode("\r\n", $inthis);
$fh = fopen("example.txt", "w");
fwrite($fh, $newarr);
fclose($fh);
}
modFile(4, '', $f);
I have a file (all.txt) with the following:
11111111111, 22222222222, 33333333333, 44444444444
That I wish to display like this:
11111111111
22222222222
33333333333
44444444444
and to add a space then some text after each number where the text is the same on each line:
11111111111 text here
22222222222 text here
33333333333 text here
44444444444 text here
I have an html form that passes the custom text to be appended to each line.
I need to keep the file all.txt intact then save the newly formatted file with a different name.
I have tried putting variables into the implode where I currently have the "\r\n" but this does not work.
Any help very much appreciated.
Thanks in advance!
A few notes about your code: You are passing $pos to the function but it will get overwritten in the foreach. Also the foreach is empty, so what's it good for? And I don't see you use $text anywhere either.
To achieve your desired output, try this instead:
file_put_contents(
'/path/to/new.txt',
preg_replace(
'/[^\d+]+/',
' some text' . PHP_EOL,
file_get_contents('all.txt')
)
);
The pattern [^\d+]+ will match any string that is not a consecutive number and replace it with "some text " and a new line.
A somewhat more complicated version achieving the same would be:
file_put_contents(
'/path/to/new.txt',
implode(PHP_EOL, array_map(
function ($number) {
$message = filter_var(
$_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS
);
return sprintf('%s %s', trim($number), $message);
},
array_filter(str_getcsv(file_get_contents('/path/to/all.txt')))
)
));
This will (from the inside out):
Load the content of all.txt and parse it as CSV string into an array. Each array element corresponds to a number.
Each of these numbers is appended with the message content from the POST superglobal (you dont want to use REQUEST).
The resulting array is then concatenated back into a single string where the concatenating character is a newline.
The resulting string is written to the new file.
In case the above is too hard to follow, here is a version using temp vars and no lambda:
$allTxtContent = file_get_contents('/path/to/all.txt');
$numbers = array_filter(str_getcsv($allTxtContent));
$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
$numbersWithMessage = array();
foreach ($numbers as $number) {
$numbersWithMessage[] = sprintf('%s %s', trim($number), $message);
};
$newString = implode(PHP_EOL, $numbersWithMessage);
file_put_contents('/path/to/new.txt', $newString);
It does the same thing.
Your foreach() closing brace is on the wrong place. You've missed the exact part of running the execution of the new file creation. Here:
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis, $text){
$fh = fopen("example.txt", "w");
foreach($inthis as $pos => $a){
$newarr = $a." ".$text."\r\n";
fwrite($fh, $newarr);
}
fclose($fh);
}
modFile(4, "", $f, $text);
This is for formatting your new file as you desire, however, you're not passing the new $text['message'] you want to append to your new file. You could either modify your mod_file() method or pass it within the foreach() loop while it runs.
EDIT* Just updated the whole code, should be now what you aimed for. If it does, please mark the answer as accepted.

Categories