Replace a whole line where a particular word is found in a text file
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', $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');
}
Php replace line in a file txt
You can either use the FILE_IGNORE_NEW_LINES
constant in file()
or don't use more newlines:
file_put_contents($myFile , implode('', $lines));
Or just this as it will be imploded for you:
file_put_contents($myFile , $lines);
But you'll need to add a newline here:
$lines[3] = $_POST['title'] . "\n";
So this might be the most straight forward:
$lines = file($myFile, FILE_IGNORE_NEW_LINES);
$lines[3] = $_POST['title'];
file_put_contents($myFile , implode("\n", $lines));
Replace specific line in text file using php while preserving to rest of the file
There are two solutions thanks to Cheery and Dagon.
Solution one
<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath);
//check post
if (isset($_POST["input"]) &&
isset($_POST["hidden"])) {
$line = $_POST['hidden'];
$update = $_POST['input'] . "\n";
// Make the change to line in array
$txt[$line] = $update;
// Put the lines back together, and write back into txt file
file_put_contents($filepath, implode("", $txt));
//success code
echo 'success';
} else {
echo 'error';
}
?>
Solution two
<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath);
// Get file contents as string
$content = file_get_contents($filepath);
//check post
if (isset($_POST["input"]) &&
isset($_POST["hidden"])) {
$line = $_POST['hidden'];
$update = $_POST['input'] . "\n";
// Replace initial string (from $txt array) with $update in $content
$newcontent = str_replace($txt[$line], $update, $content);
file_put_contents($filepath, $newcontent);
//success code
echo 'success';
} else {
echo 'error';
}
?>
Overwrite Line in File with PHP
If the file isn't too big, the best way would probably be to read the file into an array of lines with file(), search through the array of lines for your string and edit that line, then implode() the array back together and fwrite() it back to the file.
Replace line in text file using PHP
You don't need a regex for this. Try the following:
- Load the file into an array using
file()
and loop through the lines - Check if the string starts with
2_
- If it does, replace it with the input
$word
and concatenate it to the$result
string - If if doesn't, simply concatenate it to the
$result
string - Use
file_get_contents()
and write the result to the file
Code:
$lines = file('file.txt');
$word = 'word';
$result = '';
foreach($lines as $line) {
if(substr($line, 0, 2) == '2_') {
$result .= '2_'.$word."\n";
} else {
$result .= $line;
}
}
file_put_contents('file.txt', $result);
Now, if the replace took place, then file.txt
would contain the something like:
1_fjd
2_word
3_fks
how to replace one line of a file with php
As deceze♦ mentioned, unless the line is of fixed length, the easiest way is to process the whole file and output it to a new file.
Create a variable $newdata to append the processed data.
If your strpos statement !== false then you can change that text with the $replace_text variable and append that instead.
Once the loop has finished save your output to a new file. (If PHP has the appropriate permissions)
$file = fopen("file.dat", "a+");
$eqs = file_get_contents("file.dat");
$eqs = preg_split( "/\n/", $eqs );
$newdata = "";
foreach ($eqs as $valor) {
if(strpos($valor, $sn) !== false){
echo $valor; //this is the line to replace
$replace_text = "test";
$newdata = $newdata.$replace_text."/\n/";
} else{
$newdata = $newdata.$valor."/\n/";
}
}
$myfile = fopen("newfile.dat", "w") or die("Unable to open file!");
fwrite($myfile, $newdata);
fclose($myfile);
PHP | Replace line in large txt-file
You should use PHP's file() function for that. It will return an array containing each line.
$file = file('path/to/text.txt');
$lines = array_map(function ($value) { return rtrim($value, PHP_EOL); }, $file);
$lines[3] = 'New content for line 4';
$lines = array_values($lines);
To save it again, implode the array with newline:
$content = implode(PHP_EOL, $lines);
file_put_contents('path/to/your/file.txt', $content);
PHP: Replace line in a file or add if not found
You can do something like this:
$message_exists = false;
$filename = 'messages.txt';
$data = file($filename);
file_put_contents($filename, implode('',
array_map(function($data) use (&$message_exists){
$result = substr($data, 0, strlen('aabbcc|')) === 'aabbcc|';
if($result)
{
$message_exists = true;
}
return $result ? "aabbcc|This would be a NEW line.\n" : $data;
}, file($filename))
));
if(!$message_exists)
{
file_put_contents($filename, "aabbcc|This would be a NEW line.\n", FILE_APPEND);
}
Replace text file line by line number
If you use the fact that file_put_contents()
can take an array and just write it out, there is a simpler version which just takes the original contents of file()
(including the new lines it will load automatically) and then replace the corresponding line (using array notation [$needle]
) but add a new line onto the data (PHP_EOL
to be generic). Then just write this array out.
$arr = file('file.txt'); // text to array
$content = "";
$needle = 3; // the line number you want to edit
$replace = 'PHP script'; // the replacement text
$arr[$needle] = $replace . PHP_EOL;
file_put_contents('file.txt', $arr);
Related Topics
Remove Trailing Slash from String PHP
How to Do Aes256 Decryption in PHP
PHP Get Dropdown Value and Text
Hide Variation Info from Cart Item Title in Woocommerce 3+
Mysqli_Query(): Couldn't Fetch MySQLi Error
How to Implement Ocr on a Website Using PHP
PHP Can Static:: Replace Self::
Proper Session Hijacking Prevention in PHP
When to Use Index.PHP Instead of Index.Html
Strict Standards: Only Variables Should Be Assigned by Reference PHP 5.4
How to Pass Value from One PHP Page to Another Using Session
Use Git Smudge/Clean to Replace File Contents