Deleting characters from file
Posted: Fri Aug 31, 2007 6:12 am
How to find a particular character in a file and delete it?
Each line contains a character, like this
a
b
c
f
Each line contains a character, like this
a
b
c
f
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");Its small, i am reading it usingIs the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?
Code: Select all
file()I am using windowsLinux OS and exec() available:
Code:
exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");
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));
?>I think volka's suggestion would be:shivam0101 wrote:Its small, i am reading it usingIs the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?Code: Select all
file()
Code: Select all
$new_file_contents = preg_replace('/[aefm]\n/', '', $file_contents);