用行号替换文本文件

时间:2019-12-17 09:11:34

标签: 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

我使用以下代码进行了测试。但是它不能在主机上运行。您有更好的解决方案吗?

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

3 个答案:

答案 0 :(得分:2)

您可以使用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));

?>

答案 1 :(得分:1)

如果您使用file_put_contents()可以采用数组并将其写入的事实,则有一个更简单的版本,它仅采用file()的原始内容(包括将自动加载的新行) ),然后替换相应的行(使用数组表示法[$needle]),但是在数据上添加新行(PHP_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);

答案 2 :(得分:-1)

这是解决您问题的代码。如有疑问,请随时发表评论。

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

您测试的页面上的工作示例: https://3v4l.org/IcWGE