使用php从文本文件中删除一行

时间:2014-05-06 12:54:00

标签: php

我有一个像。的文本文件 somerandomtext

abc morerandomtext def

evenmorerandomtext

我想做的是替换" morerandomtext"使用" otherrandomtext",现在我有一个函数可以找到更多随机文本的行并在更多的随机文本中展开它。它工作正常,除了被替换的文本添加到文本文件,而不是替换" morerandomtext"。

这是我的功能

function c_replaceInFile($path,$target,$replacement){
    if(file_exists($_SERVER['DOCUMENT_ROOT'].$path)){
        $handle = fopen($_SERVER['DOCUMENT_ROOT'].$path, 'r+');
        while (($line = fgets($handle)) !== false) {
            $readLine = $line;
            if(c_findAfter($target,$readLine,true) != ""){
                $temp = explode($target,$readLine,2);
                $out = $temp[0].$replacement.$temp[1];
                //remove $line here

                fputs($handle,$out);
                break;
            }
        }
        fclose($handle);
    }else{
        getError("Error: file $path doesn't exist","otherErrors");
    }
}

我不想将文件加载到单个数组中,因为文件很大,,除非它不会使用100mb文本文件减慢/崩溃服务器

TL; DR: 我需要一个能删除$ line的函数。

我认为php没有我正在寻找的功能。没关系这个问题,我只是尝试使用mysql。

3 个答案:

答案 0 :(得分:0)

您只需制作一个新文件即可。 将未编辑的文件写入其中。编辑也。 最后用新文件覆盖上一个文件。

使用file_put_contents()覆盖。

答案 1 :(得分:0)

试试这个。

$content = file_get_contents('file.xxx');

$content = str_replace($target, $replacement, $content);

file_put_contents('file.xxx', $content);

答案 2 :(得分:0)

如果他们每天改变一次只是在半夜做一个cron工作。

我认为约翰的答案可以很好地运作。

否则尝试使用strpos它会找到您可以使用str_replace出现的出现字符串来对给定结果执行某些操作。

$a = 'abc morerandomtext def';
if (strpos($a,'morerandomtext ') !== false) {
    ***doyourthing***
}
相关问题