How to delete a certain line of a file in php: first define the operation file; then read the file data into an array; and finally delete the specified line of the existing text file.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How to delete a certain line of a file with php?
PHP Delete any line of the text file or add a line
Delete the specified line of the actual existing text file. This line can be arbitrary, that is, it is decided by the user. Deleting any line in a text file is very meaningful. For example, we use a text file to record relevant information about registered users (one piece of information per line), and now we need to delete one of them.
<?php $filename="aaa.txt";//定义操作文件 $delline=3; //要删除的行数 $farray=file($filename);//读取文件数据到数组中 for($i=0;$i<count($farray);$i++) { if(strcmp($i+1,$delline)==0) //判断删除的行,strcmp是比较两个数大小的函数 { continue; } if(trim($farray[$i])<>"") //删除文件中的所有空行 { $newfp.=$farray[$i]; //重新整理后的数据 } } $fp=@fopen($filename,"w");//以写的方式打开文件 @fputs($fp,$newfp); @fclose($fp); ?>
The text file aaa.txt is as follows:
10.8.0.1:255.255.255.0 10.8.0.2:255.255.255.0 10.8.0.3:255.255.255.0 10.8.0.4:255.255.255.0 10.8.0.5:255.255.255.0 10.8.0.6:255.255.255.0 10.8.0.8:255.255.255.0
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete a certain line of a file in php. For more information, please follow other related articles on the PHP Chinese website!