Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace a particular line in a text file using php?

Tags:

php

how to replace a particular row using php. I dont know the line number. I want to replace a line containing a particular word.

like image 681
kishore Avatar asked Jun 09 '10 08:06

kishore


People also ask

How do you write to a new line in PHP?

Use PHP_EOL which outputs \r\n or \n depending on the OS. Don't get in trouble, always use \n unless you want to open the file in a specific OS - if so, use the newline combination of that OS, and not the OS you're running PHP on ( PHP_EOL ).

How do I read the last line of a text file in PHP?

The 'fseek' function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.

How do I make the first line of a file read only in PHP?

If you ABSOLUTELY know the file exists, you can use a one-liner: $line = fgets(fopen($file, 'r')); The reason is that PHP implements RAII for resources. That means that when the file handle goes out of scope (which happens immediately after the call to fgets in this case), it will be closed.


Video Answer


1 Answers

One approach that you can use on smaller files that can fit into your memory twice:

$data = file('myfile'); // reads an array of lines function replace_a_line($data) {    if (stristr($data, 'certain word')) {      return "replacement line!\n";    }    return $data; } $data = array_map('replace_a_line',$data); file_put_contents('myfile', implode('', $data)); 

A quick note, PHP > 5.3.0 supports lambda functions so you can remove the named function declaration and shorten the map to:

$data = array_map(function($data) {   return stristr($data,'certain word') ? "replacement line\n" : $data; }, $data); 

You could theoretically make this a single (harder to follow) php statement:

file_put_contents('myfile', implode('',    array_map(function($data) {     return stristr($data,'certain word') ? "replacement line\n" : $data;   }, file('myfile')) )); 

Another (less memory intensive) approach that you should use for larger files:

$reading = fopen('myfile', 'r'); $writing = fopen('myfile.tmp', 'w');  $replaced = false;  while (!feof($reading)) {   $line = fgets($reading);   if (stristr($line,'certain word')) {     $line = "replacement line!\n";     $replaced = true;   }   fputs($writing, $line); } fclose($reading); fclose($writing); // might as well not overwrite the file if we didn't replace anything if ($replaced)  {   rename('myfile.tmp', 'myfile'); } else {   unlink('myfile.tmp'); } 
like image 197
gnarf Avatar answered Sep 30 '22 04:09

gnarf