Forum Moderators: coopster
I am try to read from file A
then read from file B
I need to read all the words from file B and extract them from A
for instance File A = the boy ran down the road
file B = ran, road
the ouput should of A should be boy down road
then output this to the screen, any takers
I have this so far, but i need to subtitute the variable $Key with a file.
<?
$key = array("/ the /", "/the /", "/ is /", "/ my /", "/ thy /", "/i /");
//load file into $fc array
$fc=file("psalm.txt");
//open output file and use "w" to clear file and write to it
$f=fopen("output.txt","w");
//loop through array using foreach
foreach($fc as $line)
{
$line = strtolower ($line); //change to lower case
//if (!strstr($line,$key)) //look for $key in each line
$line = preg_replace ($key , " " , $line);
fputs($f,$line); //place $line back in file
}
fclose($f);
if (!($fc=fopen("output.txt","r")))
exit("Unable to open file.");
while (!feof($fc))
{
$x=fgetc($fc);
echo $x;
}
fclose($fc);
?>
How big are these files? Can you just do this
$input = file_get_contents [php.net]($filename);
$output = str_replace [php.net]($keys, '', $input);
And then write the string to your output file?
$b = file_get_contents('fileb.txt');
$keys = explode(',',$b);
$a = file_get_contents('filea.txt');
$new_a = str_replace($keys, '', $a);
The problem with this code is it replaces strings, not just whole words. So if file b has
dog,foo
and file a has
Despite his dogged determination he was foobarred
The ouput is
Despite his ged determination he was foored
We can work around that with regular expressions or padding the search terms or whatever you need if you must search for whole words only.
<?php
// keys.txt is in format 'word, anotherword, yetanotherword';
$keysfile = 'keys.txt';
$readfile = 'psalm.txt';
$writefile = 'psalmreplaced.txt';
$keys = file_get_contents($keysfile);
$words = explode(',' $keys);
$destination = file_get_contents($readfile);
foreach($keys as $v){
$destination = preg_replace('#[\W]'.trim($v).'[\W]#', '', $destination);
}
$handle = fopen($writefile, 'w');
fwrite($handle, $destination, strlen($destination);
fclose($handle);