user1037871
user1037871

Reputation: 543

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?

Upvotes: 52

Views: 139502

Answers (5)

Evan TOder
Evan TOder

Reputation: 91

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];
}

Upvotes: 0

Rachid Loukili
Rachid Loukili

Reputation: 845

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

Upvotes: 5

M. Ahmad Zafar
M. Ahmad Zafar

Reputation: 4939

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

Upvotes: 107

Adrian Goia
Adrian Goia

Reputation: 171

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

Upvotes: 8

hugsbrugs
hugsbrugs

Reputation: 3611

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

Upvotes: 14

Related Questions