How to delete any line in text file in php

王林
Release: 2023-03-06 16:50:01
Original
2547 people have browsed it

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 );
 ?>
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template