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

51

我需要打开一个文本文件并替换其中的字符串。我需要这个。

Old String: <span id="$msgid" style="display: block;">
New String: <span id="$msgid" style="display: none;">
这是我目前的代码,但是除了额外的空格之外,我没有看到文本文件有任何变化。
$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);

我应该如何做呢?


请确保您对msghistory.txt文件拥有写入权限。 - Lobo
这是正确的吗?$deletedFormat = ""'; - A Person
您有一个语法错误。$deletedFormat = ""'; 您多了一个单引号。 - Madara's Ghost
已经把那个拿掉了,谢谢。我有写入权限,但仍然不知道为什么HTML没有被写入。 - user1037871
$msgid 在你的 PHP 代码中扮演什么角色? - M. Ahmad Zafar
1
$msgid具有需要放置在样式ID属性中的值。我可能遗漏了一些小细节... - user1037871
4个回答

107

这个能行吗:

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

14

感谢您的评论。我已经编写了一个函数,当出现错误时会给出错误信息:

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

7

这个功能非常好用,快速而准确:

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

使用方法:

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

// 在进行字符串解析时,永远不要忘记EXPLODE // 它是一个强大而快速的工具


1
explode和implode比简单的str_replace慢:http://micro-optimization.com/str_replace-vs-implode-explode.html - Passer by
我可以问一下您使用 explode 和 implode 的原因吗?我遵循了您的建议,它非常有效!我只是想知道,为什么您没有直接使用 str_replace() 函数呢? - Pedroski
@Pedroski:你好亲爱的!这只是我的想法。我承认 str_replace() 可能会更快。 - Adrian Goia
谢谢,我问这个问题是因为我真的不太懂这些东西。我只知道它能工作,速度对我来说并不重要! - Pedroski

4
public function fileReplaceContent($path, $oldContent, $newContent)
{
    $str = file_get_contents($path);
    $str = str_replace($oldContent, $newContent, $str);
    file_put_contents($path, $str);
}

使用

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接