在字符串 PHP 之后编辑文本文件


Edit text file after string PHP

我需要在文本文件中的字符串("Comments:"(之后添加文本(假设单词"Hello"(以及换行符,同时还要保留后面的文本。如何添加此文本?

编辑:

我的文本文件如下所示:

Comments:
<new comment goes here>
<older comments here>

我想把我的新文本放在"<new comment goes here>"的位置,同时保留" <older comments here> ">

使用 file_put_contents

<?php
    $file = 'comm.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new person to the file
    $current .= "Write something here'n";
    // Write the contents back to the file
    file_put_contents($file, $current);
 ?>

您可以使用file_put_contents来做同样的事情。

int file_put_contents ( 字符串 $filename , 混合 $data [, int $flags = 0 [, 资源 $context ]] (

例如:

$text = explode("'n", file_get_contents('comm.txt'), 2);  
file_put_contents('comm.txt', $text[0]."'nHello'n".$text[1]); 
<?php
$file = 'comm.txt';
$wholecontent = file_get_contents($file);
$commenttoreplace= current(explode("'n", $wholecontent)); 
$newcomment=$commenttoreplace."comment what yo like to add";
file_put_contents($file, str_replace($commenttoreplace,$newcomment,$wholecontent));
?>

以上ex将起作用,请告知是否有任何问题