Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in text file using PHP

I need to open a text file and replace a string. I need this

Old String: <span id="$msgid" style="display: block;"> New String: <span id="$msgid" style="display: none;"> 

This is what I have so far, but I don't see any changes in the text file besides extra white spaces.

$msgid = $_GET['msgid'];  $oldMessage = ""; $deletedFormat = "";  // Read the entire string $str = implode("\n", file('msghistory.txt'));  $fp = fopen('msghistory.txt', 'w');  // Replace something in the file string - this is a VERY simple example $str = str_replace("$oldMessage", "$deletedFormat", $str);  fwrite($fp, $str, strlen($str)); fclose($fp); 

How can I do it?

like image 362
user1037871 Avatar asked Aug 10 '12 12:08

user1037871


People also ask

How to replace string in file using PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How to replace the word in a file in PHP?

txt', 'w'); // Replace something in the file string - this is a VERY simple example $str = str_replace("$oldMessage", "$deletedFormat", $str); fwrite($fp, $str, strlen($str)); fclose($fp);

How do I replace text in a string?

String text1 = web1. getTitle(); String text2 = text1. toString(). replace("-Click 2U - Files", "");

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.


1 Answers

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); 
like image 101
M. Ahmad Zafar Avatar answered Sep 21 '22 08:09

M. Ahmad Zafar