How to delete specified lines in txt in php

藏色散人
Release: 2023-03-09 09:14:01
Original
2337 people have browsed it

php method to delete specified lines in txt: first create a PHP sample file; then open the txt file in read and write mode; finally pass "for($n=1;$n<=$len-1; $n ){...}" method can be used to delete the specified lines in the txt.

How to delete specified lines in txt in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

php implements the code to delete the specified line in the txt document, Friends in need may wish to refer to it.

The code is as follows:

<?php
/*
* 删除txt文档中的指定行
* site www.jbxue.com
*/
function del_str_line($file,$line){
$str=&#39;&#39;;
$handle = @fopen("1.txt", "rb+");//以读写方式打开,
//建议 fopen() 打开文件时使用 &#39;b&#39; 标记。
if ($handle) {
for($i=0;$i<$line;$i++){
   $str=fgets($handle);//读取指定的行
}
//关闭文件,因为当前的文件指针已经指向了下一行
//不关闭的话,直接执行下面的重写代码,PHP会在$line+1删除指定个数的字符
rewind($handle);//重置文件指针到开头
$len=strlen($str);//计算指定行的长度
for($i=0;$i<$line-1;$i++){
   fgets($handle);//将文件指针定位到指定行的上一行
}
for($n=1;$n<=$len-1;$n++){//循环重写文件,这时候文件指针移动到指定行
   fwrite($handle,&#39; &#39;,1);//将指定行每个位置的字符用空格代替,实现删除
}
}
}
del_str_line(&#39;1.txt&#39;,3);
?>
Copy after login

The code is as above. Please prepare the txt document for testing by yourself.

[Recommended learning: PHP video tutorial]

The above is the detailed content of How to delete specified lines in txt 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