Overwrite a specific line in a text file with php [duplicate] - php

This question already has answers here:
Replace a whole line where a particular word is found in a text file
(12 answers)
Closed last year.
Need to find a simple solution to the following:
I have a php file that, when executed, should be able to replace a specific line of code within itself, with a different value on that line.
I came up with this so far:
$file = "file.php";
$content = file($file);
foreach($content as $lineNumber => &$lineContent) {
if($lineNumber == 19) {
$lineContent .= "replacement_string";
}
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);
However, that does not replace the specific line. It adds the new string on a new line and that's it. I need that specific line ERASED and then REPLACED with the new string, on that line.
How would I continue about doing that? I'd love some pointers.

Since file() creates an array, make use of the index to select the line.
Don't forget that array indexes start at 0!
$file = "file.php";
$content = file($file);
$content[19] = "replacement_string\r\n";
$allContent = implode("", $content);
file_put_contents($file, $allContent);

Your problem is the .= in the $lineContent .= "replacement_string"; line. Just use = or use the str_replace() or str_ireplace() function.

Related

Remove Line from String within txt file

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

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

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.

Remove first line form file using php [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php - efficent way to get and remove first line in file
I need to remove first line form txt file using php. Could you show me example code how to do it? I know that it's easy but I don't know php:) Thanks!
You could do this:
$file = file_get_contents(SOME_FILE);
$arr = explode('\n\r', $file);
if (isset($arr[0])) unset ($arr[0]);
$string = implode('\n\r', $arr);
file_put_contents(SOME_FILE, $string);
You could have used the search function at least. You would have found this:
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));

In PHP, if I find a word in a file, can I make the line that the word came from into a $string

I want to find a word in a large list file.
Then, if and when that word is found, take the whole line of the list file that the word was found in?
so far I have not seen any PHP string functions to do this
Use a line-delimited regular expression to find the word, then your match will contain the whole line.
Something like:
preg_match('^.*WORD.*$, $filecontents, $matches);
Then $matches will have the full lines of the places it found WORD
You could use preg_match:
$arr = array();
preg_match("/^.*yourSearch.*$/", $fileContents, $arr);
$arr will then contain the matches.
$path = "/path/to/wordlist.txt";
$word = "Word";
$handle = fopen($path,'r');
$currentline = 1; //in case you want to know which line you got it from
while(!feof($handle))
{
$line = fgets($handle);
if(strpos($line,$word))
{
$lines[$currentline] = $line;
}
$currentline++;
}
fclose($handle);
If you want to only find a single line where the word occurs, then instead of saving it to an array, save it somewhere and just break after the match is made.
This should work quickly on files of any size (using file() on large files probably isn't good)
Try this one:
$searhString = "search";
$result = preg_grep("/^.*{$searhString}.*$/", file('/path/to/your/file.txt'));
print_r($result);
Explanation:
file() will read your file and produces array of lines
preg_grep() will return array element in which matching pattern is found
$result is the resulting array.

Categories