Replace string in text file using PHP
Asked Answered
D

5

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?

Dessalines answered 10/8, 2012 at 12:17 Comment(6)
Make sure you have write permissions on the msghistory.txt fileConflagration
Is this right? $deletedFormat = ""';Phyletic
You have a syntax error. $deletedFormat = ""'; you have an extra single quote.Westfalen
taken that out thanks, I do have writing permissions. still not i dont know why the html is not writingDessalines
What is the role of $msgid in your PHP code?Parchment
the $msgid has a value that needs to be placed in the style id attribute.. It's something small im missing...Dessalines
P
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);
Parchment answered 10/8, 2012 at 12:20 Comment(0)
B
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;
}
Bukharin answered 16/6, 2014 at 9:49 Comment(0)
M
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

Merow answered 12/4, 2016 at 17:35 Comment(4)
explode, implodes are slower than a simple str_replace: micro-optimization.com/str_replace-vs-implode-explode.htmlAinsworth
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() ???Shaniceshanie
@Pedroski: Hello dear fellow! This was simply my way of thinking. I admit that str_replace() could be faster.Merow
Thanks, I ask because I don't really understand this stuff. All I know is: it woks, and speed doesn't matter to me!Shaniceshanie
G
4
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')
Gamber answered 12/9, 2021 at 21:49 Comment(0)
S
0

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];
}
Swanskin answered 8/3 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.