如何在文件中搜索文本然后将其删除?

时间:2018-01-28 15:37:21

标签: php

假设我的txt文件中的内容是:

Hello! This is a test file!

Continued...

我了解应该首先阅读文件的内容:

<?php
$file = file_get_contents("test.txt");

我该如何继续?要搜索文本:'继续...'将其删除,然后重新保存文件。

(不破坏其余内容)

2 个答案:

答案 0 :(得分:0)

如果您只是想删除&#34;续...&#34;在使用file_get_contents检索到的文字中,您可以使用str_replace,然后使用file_put_contents将修改后的内容放回文字文件中:

$filename = 'test.txt';
$content = file_get_contents($filename);
file_put_contents($filename, str_replace('Continued...', '', $content));

它实际上非常接近file_put_contents文档中提供的first example

答案 1 :(得分:0)

<?php
$file = file_get_contents("test.txt");
$newfileContetnt = str_replace('Continued...', '', $file);
file_put_conetnt($newfileContetnt);