How to delete specified lines in a file in php

藏色散人
Release: 2023-03-04 12:22:02
Original
3153 people have browsed it

php method to delete file lines: first define the operation file; then determine the number of lines to be deleted; then read the file data into the array and determine the deleted lines; finally delete the files through the "trim" function All blank lines will suffice.

How to delete specified lines in a file in php

Recommended: "PHP Video Tutorial"

PHP Delete any line or add a line in the text file

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

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

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

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

Related labels:
php
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