Home >Backend Development >PHP Problem >How to delete text file content in php

How to delete text file content in php

藏色散人
藏色散人Original
2021-06-08 09:16:492107browse

php method to delete the content of a text file: first create a PHP sample file; then define the operation file and determine the row keywords to be deleted; then read the file data into an array; and finally delete the specified content of the file. .

How to delete text file content in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to delete the content of text files with php?

The code is as follows:

<?php
$filename="aaa.txt";//定义操作文件
$dellinekey=&#39;13800&#39;; //要删除的行关键字
$delcount=0;//已删除的行数
$farray=file($filename);//读取文件数据到数组中
for($i=0;$i<count($farray);$i++)
{   
  if($delcount == 0 && substr_count($farray[$i],$dellinekey) > 0)  //先判断是否已删除一次,再判断当前行是否包含关键字,是则删除
  {   
     $delcount++;//标记删除一次
    continue;
  }   
  if(trim($farray[$i])<>"")  //删除文件中的所有空行
  {   
      $newfp.=$farray[$i];    //重新整理后的数据
  }   
}   
$fp=@fopen($filename,"w");//以写的方式打开文件
@fputs($fp,$newfp);
@fclose($fp);
?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete text file content in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn