Php 按行号替换文本文件行

Php 按行号替换文本文件行,php,Php,如何根据行号从文本文件中删除一行并替换为新行? 例如,使用php编辑file.txt: 运行脚本之前: Line 1: replace Line 2: line Line 3: with Line 4: script Line 1: replace Line 2: line Line 3: with Line 4: PHP script 运行后脚本: Line 1: replace Line 2: line Line 3: with Line 4: script Line 1: repla

如何根据行号从文本文件中删除一行并替换为新行? 例如,使用php编辑file.txt: 运行脚本之前:

Line 1: replace
Line 2: line
Line 3: with
Line 4: script
Line 1: replace
Line 2: line
Line 3: with
Line 4: PHP script
运行后脚本:

Line 1: replace
Line 2: line
Line 3: with
Line 4: script
Line 1: replace
Line 2: line
Line 3: with
Line 4: PHP script
我使用以下代码进行了测试。但它不在主机上运行。你有更好的解决办法吗

$arr = file('file.txt'); // text to array

$content = "";
$needle = 3; // the line number you want to edit
$replace = 'PHP script'; // the replacement text

foreach($arr as $key => $line) {
    if($line[0] == $needle) {
        $arr[$key] = $needle . " $replace" . PHP_EOL;
    }
    $content .= $arr[$key]; // rebuild your text file
}

echo 'The new text file contents:' . PHP_EOL;
echo $content;
// overwrite text file with edited content
file_put_contents('file.txt', $content);

下面是修复您的问题的代码。如果有任何不清楚的地方,请随时发表评论

<?php
// Please note that starting index in a file, array is ZERO not ONE as in your example

$edited_file_data = file('file.txt', FILE_IGNORE_NEW_LINES ); // text to array which ommits new lines (thanks Nigel)

$line_to_replace     = 3;            // the line number you want to edit
$replacement_content = 'PHP script'; // the replacement text


$edited_file_data[$line_to_replace] = $replacement_content;

echo 'The new text file contents:' . PHP_EOL;

$new_file_data_as_string = implode("\r\n", $edited_file_data);
echo $new_file_data_as_string;

// overwrite text file with edited content
file_put_contents('file.txt', $new_file_data_as_string);
?>
测试页面上的工作示例:

您可以使用array_splice方法修改使用file读取文件时创建的数组,也可以修改该方法以搜索要替换的内容

<?php

    $file=__DIR__ . '/srctext.txt';

    $line=4;
    $replace = 'Banana';


    $lines=file( $file, FILE_IGNORE_NEW_LINES );
    array_splice( $lines, $line, 1, $replace );
    file_put_contents($file,implode("\n",$lines));

?>
如果您使用file\u put\u contents可以获取一个数组并将其写出的事实,那么有一个更简单的版本,它只获取文件的原始内容,包括它将自动加载的新行,然后使用数组符号[$needle]替换相应的行,但在数据PHP\u EOL上添加一个新行作为通用。然后写下这个数组

$arr = file('file.txt'); // text to array

$content = "";
$needle = 3; // the line number you want to edit
$replace = 'PHP script'; // the replacement text

$arr[$needle] = $replace . PHP_EOL;
file_put_contents('file.txt', $arr);

但是它不在主机上运行-那么会发生什么呢?它在本地有效吗?做过调试吗?您对该文件有写权限吗?因为$line[0]永远不会===$needle您认为$line[0]会是什么。它将是每行字符串的第一个字符,即它将是L,因为字符串可以被视为ArrayS777。联机运行,但不在主机上运行。那条评论应该回答什么?所以你的示例输入文件实际上与真实文件完全不同,这很有用。你的代码中有一些语法错误和其他问题,值得测试。我在记事本中写下了答案,第一次没有注意到它们。我更新了代码。@besciualex谢谢你的回答。但运行后会创建脚本空行。这取决于运行脚本的操作系统。使用\n而不是\r\n。如果你根本不想要任何行,也可以使用简单的空引号。虽然这不是我的否决票-使用没有文件的文件\u忽略\u新的\u行将意味着数组值将保留新行,当你内爆并添加新行时,每次都会添加额外的行。