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.
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=''; $handle = @fopen("1.txt", "rb+");//以读写方式打开, //建议 fopen() 打开文件时使用 'b' 标记。 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,' ',1);//将指定行每个位置的字符用空格代替,实现删除 } } } del_str_line('1.txt',3); ?>
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!