php method to delete specified lines: first create a PHP sample file; then define the operation file and determine the number of lines to be deleted; then read the file data into an array; finally determine the deleted lines and re- Just organize the data.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
PHP Delete any line of the text file or Add a line
to delete the specified line of the existing text file. This line can be arbitrary, that is, it is decided by the user. Deleting any line of a text file is very meaningful. For example, we use a text file to record relevant information of 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
Add a line of data to the last line
<? php $filename = " aaa.txt " ; // 定义操作文件 $fcontent = file ( $filename ); // file()把整个文件读入一个数组中 $fp = fopen ( " $filename " , " a " ); $str = " 10.8.0.9:255.255.255.0\n " ; fwrite ( $fp , $str ); ?>
[Recommended learning: "PHP Video Tutorial"]
The above is the detailed content of How to delete specified lines in php. For more information, please follow other related articles on the PHP Chinese website!