Replace string in text file using PHP-ThrowExceptions

Exception or error:

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));

How can I do it?

How to solve:

Does this work:

$msgid = $_GET['msgid'];

$oldMessage = '';

$deletedFormat = '';

//read the entire string

//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);


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' => '');
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                    $Result["status"] = 'success';
                   $Result["message"] = 'Error while writing file';
            catch(Exception $e)
                $Result["message"] = 'Error : '.$e;
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    return $Result;


This works like a charm, fast and accurate:

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


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

Leave a Reply

Your email address will not be published. Required fields are marked *