使用PHP替换文本文件中的字符串

时间:2022-10-17 11:34:23

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?

我该怎么做?

3 个解决方案

#1


65  

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

#2


11  

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

#3


3  

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

//当谈到字符串解析时,永远不要忘记EXPLODE //这是一个强大而快速的工具

#1


65  

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

#2


11  

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

#3


3  

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

//当谈到字符串解析时,永远不要忘记EXPLODE //这是一个强大而快速的工具