Deleting characters from file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
shivam0101
Forum Contributor
Posts: 197
Joined: Sat Jun 09, 2007 12:09 am

Deleting characters from file

Post by shivam0101 »

How to find a particular character in a file and delete it?

Each line contains a character, like this

a
b
c
f
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Is the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

Linux OS and exec() available:

Code: Select all

exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");
There are 10 types of people in this world, those who understand binary and those who don't
shivam0101
Forum Contributor
Posts: 197
Joined: Sat Jun 09, 2007 12:09 am

Post by shivam0101 »

Is the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?
Its small, i am reading it using

Code: Select all

file()

Linux OS and exec() available:

Code:
exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");
I am using windows
mcog_esteban
Forum Contributor
Posts: 127
Joined: Tue Dec 30, 2003 3:28 pm

Post by mcog_esteban »

Try something like:

Code: Select all

<?php
$remove[] = 'a';
$remove[] = 'd';

$contents = file_get_contents("file.txt");
$explode = explode("\n", $contents);

$final = array_diff($explode, $remove);
$handle = fopen("file.txt", "w");
fwrite($handle, implode("\n", $final));

?>
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

shivam0101 wrote:
Is the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?
Its small, i am reading it using

Code: Select all

file()
I think volka's suggestion would be:

Code: Select all

$new_file_contents = preg_replace('/[aefm]\n/', '', $file_contents);
There are 10 types of people in this world, those who understand binary and those who don't
shivam0101
Forum Contributor
Posts: 197
Joined: Sat Jun 09, 2007 12:09 am

Post by shivam0101 »

Thanks, its working fine.
Post Reply