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

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

How to&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 "replaement 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');
}

Answer:

You have to overwrite the entire file.

So, for the relatively small file, read file into array, search for the word, replace found row, write all the rest into file.

For the big file the algorithm is slightly different, but quite the same in general.

Important part is file locking

that’s why we prefer a database.

Answer:

You can also use multi-line mode with regular expressions

preg_match_all('/word}/m', $textfile, $matches);

this is, of course, assuming it’s a smaller document at the ready and loaded. Otherwise, the other answers are far more ‘real-world’ of a solution.

Answer:

$filedata = file('filename');
$newdata = array();
$lookfor = 'replaceme';
$newtext = 'withme';

foreach ($filedata as $filerow) {
  if (strstr($filerow, $lookfor) !== false)
    $filerow = $newtext;
  $newdata[] = $filerow;
}

Now $newdata contains the file contents as an array (use implode() if you don’t want array) with the line containing “replaceme” replaced with “withme”.

Answer:

If you don’t know the line, you will have to search over all lines.

Either iterate over the file line by line or read the file into memory all at once.
Then either find the word with a combination of strpos and str_replace or
use preg_replace.

If you iterate, simply use strpos and replace the line once it didn’t return FALSE. Then save the file back to disk.

Answer:

You could turn the file into an array using the explode(); function, edit any item in the array, use the implode(); function to turn the array back into a string, then you can put the string back into the file using the file_put_contents(); function. This is shown in the following function :

function file_edit_contents($file_name, $line, $new_value){
  $file = explode("\n", rtrim(file_get_contents($file_name)));
  $file[$line] = $new_value;
  $file = implode("\n", $file);
  file_put_contents($file_name, $file);
}

Answer:

This is good if you are looking for a substring (ID) in a line and want to replace the old line with the new one.

Code:

$id = "123";
$new_line = "123,Programmer\r"; // We're not changing the ID, so ID 123 remains.
$contents = file_get_contents($dir);
$new_contents= "";
if( strpos($contents, $id) !== false) { // if file contains ID
    $contents_array = preg_split("/\r\n|\r|\n/", $contents);
    foreach ($contents_array as &$record) {    // for each line
        if (strpos($record, $id) !== false) { // if we have found the correct line
            $new_contents .= $new_line; // change record to new record
        }else{
            $new_contents .= $record . "\r";
        }
    }
    file_put_contents($dir, $new_contents); // save the records to the file
    echo json_encode("Successfully updated record!");
}
else{
    echo json_encode("failed - user ID ". $id ." doesn't exist!");
}

Example:

Old file:

ID,occupation

123,student

124,brick layer

Running the code will change file to:

New file:

ID,occupation

123,programmer

124,brick layer

Answer:

Maybe this could help:

$data = file("data.php");

for($i = 0;$i<count($data);$i++){
    echo "<form action='index.php' method='post'>";
    echo "<input type='text' value='$data[$i]' name='id[]'><br>";
}

echo "<input type='submit' value='simpan'>";
echo "</form>";

if(isset($_POST['id'])){
    file_put_contents('data.php',implode("\n",$_POST['id'])) ;
}

Answer:

You can do like this:

$file = file('data.txt'); 
$data = 'new text';
$some_index = 2;
foreach($file as $index => $line){

   if($index == $some_index){
       $file[$index] = $data . "\n";
   }

}

$content = implode($file);
file_put_contents('data.txt', $content);