如何使用PHP从文本文件中删除某些行? [英] How to Remove Some Line from Text File Using PHP?

查看:138
本文介绍了如何使用PHP从文本文件中删除某些行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含此数据的文本文件:

I have a text file contains this data :

947 11106620030 Ancho Khoren MKK6203简介 忙2,00
948 balblalbllablab
949 balblalbllablab
950 balblalbllablab
951 11106620031 Adagasa Goo MKB6201内部经济 3,00
952 balblalbllablab
953 balblalbllablab
954 balblalbllablab
962 11106620032 Fumiou Moon MKB6201世界之书 3,00

947 11106620030 Ancho Khoren MKK6203 Introduction Busy 2,00
948 balblalbllablab
949 balblalbllablab
950 balblalbllablab
951 11106620031 Adagasa Goo MKB6201 Economy Inside 3,00
952 balblalbllablab
953 balblalbllablab
954 balblalbllablab
962 11106620032 The Fumiou Moon MKB6201 The Book of World 3,00

但是,我需要删除所有包含"balblabllablab"的行,而只保留tge特定的数据行,如下所示:

However, I need to remove all the lines containing 'balblabllablab' and just leave tge specific lines of data, as shown below:

947 11106620030 Ancho Khoren MKK6203简介 忙2,00
951 11106620031 Adagasa Goo MKB6201
内部经济3,00
962 11106620032伏见月亮MKB6201 世界之书3,00

947 11106620030 Ancho Khoren MKK6203 Introduction Busy 2,00
951 11106620031 Adagasa Goo MKB6201
Economy Inside 3,00
962 11106620032 The Fumiou Moon MKB6201 The Book of World 3,00

我知道如何打开和写入文件以及关闭文件,但是我不知道如何使用php删除行/内容.如何使用php从文件中删除不需要的行?

I know how to open and write to a file aswell as closing the file, but i don't know how to remove lines / content using php. How can I remove the unneeded lines from a file using php?

推荐答案

使用file($path)函数将行放入数组中,然后遍历该数组.

Use the file($path) function to get the lines into an array, then loop through it.

$lines = file($path, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
  if(stristr($line, $remove)) unset($lines[$key]);

$data = implode('\n', array_values($lines));

$file = fopen($path);
fwrite($file, $data);
fclose($file);

这篇关于如何使用PHP从文本文件中删除某些行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆