Page 1 of 1

Deleting characters from file

Posted: Fri Aug 31, 2007 6:12 am
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

Posted: Fri Aug 31, 2007 6:19 am
by volka
Is the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?

Posted: Fri Aug 31, 2007 6:23 am
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");

Posted: Fri Aug 31, 2007 6:27 am
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

Posted: Fri Aug 31, 2007 6:34 am
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));

?>

Posted: Fri Aug 31, 2007 6:36 am
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);

Posted: Fri Aug 31, 2007 7:06 am
by shivam0101
Thanks, its working fine.