52

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?

6
  • Make sure you have write permissions on the msghistory.txt file Commented Aug 10, 2012 at 12:19
  • Is this right? $deletedFormat = ""'; Commented Aug 10, 2012 at 12:20
  • You have a syntax error. $deletedFormat = ""'; you have an extra single quote. Commented Aug 10, 2012 at 12:21
  • taken that out thanks, I do have writing permissions. still not i dont know why the html is not writing Commented Aug 10, 2012 at 12:31
  • 1
    the $msgid has a value that needs to be placed in the style id attribute.. It's something small im missing... Commented Aug 10, 2012 at 12:45

5 Answers 5

107

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); 
Sign up to request clarification or add additional context in comments.

Comments

14

Thanks to your comments. I've made a function that give an error message when it happens:

/** * Replaces a string in a file * * @param string $FilePath * @param string $OldText text to be replaced * @param string $NewText new text * @return array $Result status (success | error) & message (file exist, file permissions) */ function replace_in_file($FilePath, $OldText, $NewText) { $Result = array('status' => 'error', 'message' => ''); if(file_exists($FilePath)===TRUE) { if(is_writeable($FilePath)) { try { $FileContent = file_get_contents($FilePath); $FileContent = str_replace($OldText, $NewText, $FileContent); if(file_put_contents($FilePath, $FileContent) > 0) { $Result["status"] = 'success'; } else { $Result["message"] = 'Error while writing file'; } } catch(Exception $e) { $Result["message"] = 'Error : '.$e; } } else { $Result["message"] = 'File '.$FilePath.' is not writable !'; } } else { $Result["message"] = 'File '.$FilePath.' does not exist !'; } return $Result; } 

Comments

8

This works like a charm, fast and accurate:

function replace_string_in_file($filename, $string_to_replace, $replace_with){ $content=file_get_contents($filename); $content_chunks=explode($string_to_replace, $content); $content=implode($replace_with, $content_chunks); file_put_contents($filename, $content); } 

Usage:

$filename="users/data/letter.txt"; $string_to_replace="US$"; $replace_with="Yuan"; replace_string_in_file($filename, $string_to_replace, $replace_with); 

// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

4 Comments

explode, implodes are slower than a simple str_replace: micro-optimization.com/str_replace-vs-implode-explode.html
May I ask why you use explode, implode? I followed your advice and it works great! I'm just wondering, Why you didn't just use str_replace() ???
@Pedroski: Hello dear fellow! This was simply my way of thinking. I admit that str_replace() could be faster.
Thanks, I ask because I don't really understand this stuff. All I know is: it woks, and speed doesn't matter to me!
5
public function fileReplaceContent($path, $oldContent, $newContent) { $str = file_get_contents($path); $str = str_replace($oldContent, $newContent, $str); file_put_contents($path, $str); } 

Using

fileReplaceContent('your file path','string you want to change', 'new string') 

Comments

1

Slight mod to Rachid's fantastic best answer:

/* -------------------------------------------------------------- function to open a file [$path] and replace content in it [$oldContent] with [$newContent] and return the altered content --------------------------------------------------------------- */ function fileReplaceContent($path, $oldContent, $newContent) { // Check if the file exists and is readable if(!file_exists($path) || !is_readable($path)) { return [false, "File [" . $path . "] does not exist or is not readable."]; } $content = file_get_contents($path); // Read the content of the file if($content === false) { return [false, "Error opening or reading file at [" . $path . "]"]; } if (!is_writable($path)) // file can't be written to { return [false, "File [" . $path . "] is not writable."]; } // Replace the text $modifiedContent = str_replace($oldContent, $newContent, $content); return [true, $modifiedContent]; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.