Replace String in Text File Using PHP

Replace string in text file using PHP

Does this work:

$msgid = $_GET['msgid'];

$oldMessage = '';

$deletedFormat = '';

//read the entire string
$str=file_get_contents('msghistory.txt');

//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);

//write the entire string
file_put_contents('msghistory.txt', $str);

How to find and replace text in text file using php?

There is an error in your code.

$lines = file($myFile, FILE_IGNORE_NEW_LINES);

should be

$lines = file($myfile, FILE_IGNORE_NEW_LINES);

because you're declaring
$myfile = 'test.txt';

Note the usage of smaller case f in file name.

Now, coming to your question.

You want to replace some lines in the file with user input.

Let's assume that you want to replace the text THIS SHOULD BE REPLACED.
For that, you could use the code something line below:

<?PHP
$myfile = './test.txt';
$lines = file($myfile, FILE_IGNORE_NEW_LINES);

$textToBeReplaced = "THIS SHOULD BE REPLACED";

$index = array_search($textToBeReplaced, $lines);
if (false !== $index) {
$lines[$index] = $_POST['title'] ?? '';
}
file_put_contents($myFile , implode("\n", $lines));
?>

PHP Remove/Replace string from a text file

This works well.

But as mentioned will remove Joesephine, too

$lines  = file('names.txt');
$search = 'joe';

$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $line;
}
}
file_put_contents('names2.txt', $result);

PHP Replace string in text file using

Use strpos

foreach ($file as $n => $line) {
if (strpos($line, $membername) === 0) { // Line starts with 'membername'
$file[$n] = $membername . ' = ' . $displayname; // Replace displayname
}
}

Replacing words in a file, using another file in PHP

str_replace can take an array of strings as its first parameter, and it will find and replace each of them in the target string. So here

$chng = str_replace("stopwords", 'STOP', $x);

"stopwords" needs to be an array $stopwords containing the list of words from that file.

Probably the easiest way to get that array is to use file, a function that reads a file into an array.

$stopwords = file('stopwords.txt', FILE_IGNORE_NEW_LINES);
$chng = str_replace($stopwords, 'STOP', $x);

FILE_IGNORE_NEW_LINES is needed because otherwise the strings in the array will include the newlines, and consequently probably won't match anything in your other file.


Sort of a sidenote, but file_put_contents doesn't return the new contents, it returns the number of bytes written to the file. So if you want to see the altered text, just echo $chng; instead of $new.

Find and replace in a file

You could read the entire file in with file_get_contents(), perform a str_replace(), and output it back with file_put_contents().

Sample code:

<?php

$path_to_file = 'path/to/the/file';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH", ",H", $file_contents);
file_put_contents($path_to_file, $file_contents);

?>

Replace valuie in text file with php

PHP gives the options of reading, writing, and appending to files.

You need to open the file, read all content in, and then overwrite the file. You will get duplicate entries using append.

Here is an example code from https://www.w3schools.com/php/php_file_create.asp:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

For your code:

<?php
$name = $_POST['name'];
$mydb = file('./DB/users.txt');

$output = array();
foreach($mydb as $line) {
if(stristr($line,$name)) {
$pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);

// Glue the variables back together and overwrite $line so that it gets up in the array
$line = $name & "|" $position & "|" $email & "|" $password & "|" $atype & "\r";
}
// put everything in the $output array so that it can be writen to file after this loop
array_push($output, $line);
}
fclose($mydb);

// Write your output to file
$mydb = fopen('./DB/users.txt', "w") or die("Unable to open file!");
foreach($output as $line) {
fwrite($mydb, $line);
}
fclose($mydb);
?>

Check and replace text in a string from a text file

Though you didn't give any example from sample.log and filters.txt, I think you need to trim each $filter because of line-break.

Try:

<?php
// OPEN LOG FILE FOR READING
$file = array_reverse( file( 'sample.log' ) );

// OPEN FILTERS LIST
$filters = file( 'filters.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );

// START MAIN LOOP (SHOWS LAST X LINES FROM TEXT FILE)
$limit = 100;

// BECAUSE $file STARTS WITH 0
$limit -= 1;

foreach ( $file as $line => $line_content ) {
if ( $line == $limit ) {
break;
}

$data = explode( ' ', $line_content, 3 );
$highlight = $data[ 2 ];

// CHECK FOR FILTERS AND HIGHLIGHT IF MATCHED
foreach ( $filters as $filter ) {
if ( strpos( $highlight, ',' . $filter . ' ,' ) !== false ) {
$highlight = str_replace( $filter, '<font class="highlight">' . $filter . '</font>', $highlight );
}
}

// PRINT LIST
echo '<div class="code1a">';
echo '<font class="time">', $data[ 0 ], ' ', $data[ 1 ], '</font>';
echo '<br />';
echo $highlight;
echo '</div>';
}

Find and Replace a string in more than one text file in PHP

You can use useful glob(), internal PHP function

$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');

So for your specific case:

<?php
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Paul",",HHH",$file_contents);
file_put_contents($path_to_file,$file_contents);
}
?>

Find string and replace multiple values in a large text file using PHP

There is something not fully understandable in your question and code, of course it can be written in more optimal way.

However considering the current code you share, I suppose this changed variant the one you need.

<?php
$dir = "Example.txt";
$search = "<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>";
$replacement = " <TR><TD>Max Speed:</TD> <TD>10000</TD></TR>";
$maxbytes = "MaxBytes[192.168.1.1]: ";
$new_line = "MaxBytes[192.168.1.1]: \r";
$newmaxbytes = "MaxBytes[192.168.1.1]: 20000";

///// Change Max Speed
function find_line_number_by_string($dir, $search, $case_sensitive=false ) {
$line_number = [];
if ($file_handler = fopen($dir, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search);
$line = strtolower($line);
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number[] = $i;
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or dir";
}

return $line_number;
}

$line_number = find_line_number_by_string($dir, $search);
var_dump($line_number);

$lines = file($dir, FILE_IGNORE_NEW_LINES);
if(!empty($line_number)) {
$lines[$line_number[0]] = $replacement;
}

file_put_contents($dir , implode("\n", $lines));

///// Change MaxBytes

$contents = file_get_contents($dir);
$new_contents= "";
if( strpos($contents, $maxbytes) !== 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, $maxbytes) !== false) { // if we have found the correct line
$new_contents .= $new_line; // change record to new record
}else{
$new_contents .= $record . "\n";
}
}

file_put_contents($dir, $new_contents, LOCK_EX);

$fhandle = fopen($dir,"r");
$content = fread($fhandle,filesize($dir));
$content = str_replace($maxbytes, $newmaxbytes, $content);
$fhandle = fopen($dir,"w");
fwrite($fhandle,$content);
fclose($fhandle);

}else{}

?>

If it does not works the way you need, please contact me, I'll update the answer..



Related Topics



Leave a reply



Submit