daksh21ubuntu
daksh21ubuntu

Reputation: 276

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

Upvotes: 1

Views: 9609

Answers (4)

MaNKuR
MaNKuR

Reputation: 2704

$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!!!

Upvotes: 1

symcbean
symcbean

Reputation: 48387

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

Upvotes: 0

aderuwe
aderuwe

Reputation: 1013

You could shorten that to:

$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);

Upvotes: 2

user1646111
user1646111

Reputation:

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

Upvotes: 0

Related Questions