Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php从文本文件中删除一行_Php - Fatal编程技术网

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

使用php从文本文件中删除一行,php,Php,我有一个像这样的文本文件 一些随机文本 abc文本定义 伊文莫尔随机文本 我想做的是,用“otherrandomtext”替换“morerandomtext”,现在我有一个函数,可以找到包含morerandomtext的行,并在morerandomtext处分解它。它工作正常,只是将替换的文本添加到文本文件中,而不是替换“morerandomtext” 这是我的函数 function c_replaceInFile($path,$target,$replacement){ if(file

我有一个像这样的文本文件 一些随机文本

abc文本定义

伊文莫尔随机文本

我想做的是,用“otherrandomtext”替换“morerandomtext”,现在我有一个函数,可以找到包含morerandomtext的行,并在morerandomtext处分解它。它工作正常,只是将替换的文本添加到文本文件中,而不是替换“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;博士: 我需要一个函数,将删除$line


我假设php没有我想要的函数。不管这个问题如何,我将尝试使用mysql。

您只需创建一个新文件即可。 将未编辑的文件写入其中。该报告也进行了编辑。 最后,用新文件覆盖上一个文件

使用文件内容()覆盖。

试试这个

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

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

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

如果他们一天换一次,就在半夜里干一件无聊的工作。 我认为约翰的回答可以很有效

否则,请尝试使用它查找可用于对给定结果执行某些操作的发生字符串

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

正如我所说,这些文件将是巨大的。复制一行需要一段时间。它的作用与我的函数相同-添加新行而不是替换它。@user3569990这是因为您在同一文件中读写,因此新行会被修改。尝试使用其他名称保存文件,然后覆盖现有文件。或者查看更新的答案。@user3569990甚至可以处理大文件。