1

I have a text file contains this data :

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

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 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

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?

2
  • 1
    Open the file, read it line by line, open a new file and write the desired lines in it and dont write the ones you want to remove. Commented Jan 10, 2013 at 4:22
  • Yusufmm - your comment and code snippet aren't doing what @HankyPanky was describing. Commented Jan 10, 2013 at 4:45

2 Answers 2

9

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

and how to remove the 948, 949, 950 number ?
That will be removed as part of the line also. When I use unset($lines[$key]), that removes the entire line from the array of lines.
must use "\n" instead of '\n'for effective. and two params of fopen is needed w for write. and so I don't know why need to array_values for get array or reindexing in here?! (I EDITED THE ANSWER)
1

Contents in the file are not clear, what exactly you want to take from the text file?

Usually using regular expression you can fetch the required content, Only if it have some common pattern.

Can you please post the complete file content and explain what exactly you want to filter from it.

refer : http://php.net/manual/en/function.preg-match.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.