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

How to delete any line in text file in php

王林
王林Original
2020-10-13 13:53:262576browse

php method to delete any line in a text file: 1. Specify the operating file and the number of lines to be deleted; 2. Read the file data into the array; 3. Delete the specified line in the file; 4. Reorganize the file data; 5. Rewrite the deleted data file to the original file.

How to delete any line in text file in php

Code implementation:

(Recommended tutorial: php video tutorial)

<? 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 );
 ?>

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

Related recommendations: php training

The above is the detailed content of How to delete any line in text file 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