Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my txt file looks like this

text
sub text 1
sub text 2
sub text 3
text2
sub text2 1
sub text2 2
sub text2 3
text3
sub text3 1
sub text3 2
sub text3 3
so i want to search for text2 and then insert text with tab right below it or on the last line just befor text3


Below is the code i got to search for the string


outcome wanted

add new text

text
sub text 1
sub text 2
sub text 3
text2
sub text2 1
sub text2 2
sub text2 3
new text
text3
sub text3 1
sub text3 2
sub text3 3

What I have tried:

<pre lang="PHP"><?php
$input = "text2;
function find_value($input) {
$handle = @fopen("/users/edwin/list.txt", "r");
if ($handle) {
  while (!feof($handle)) {
    $entry_array = explode(":",fgets($handle));
    if ($entry_array[0] == $input) {
      return $entry_array[1];
      }
    }
  fclose($handle);
  }
return NULL;
}
?>
Posted
Updated 22-Jul-21 20:24pm

1 solution

The only way to insert anything in a text file is to create a new output file, then copy everything from the input file up to the insert point to it, add the new information, then copy the rest of the file to it as well.
At the end, you close both files, delete the input file, and rename the output.

Text files don't have lines - they are just a sequence of characters some of which are interpreted as an end-of-line marker - so inserting into an existing file is not possible.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900