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!
OK been trying to read on this for about a week on and off and I cant get this to work. The code below needs to read a flat file, find a string that starts with Counterfile and have anything else after that on its own line. Replace it with a with the Counterfile but a new path after that, Again its on its own line. I got it to read just that one line, but I cant figure out how to replace it on the text file and write the new information on to the file. Any help Please
$file = file("yourfile");
while (list($arr) = each($file)){
// then here do your replace thing as an if $file == what it's supposed to match.
if ($fileї$arr] == "what it should match"){
$fileї$arr] = "what it should become";
}
}
// to write to the file
$a1 = fopen("yourfile", "w+");
flock($a1,2);
foreach ($file as $key){
$fw = fwrite($a1, $key);
}
fclose($a1);
the trick is to first get all the contents of the file into an array. then alter that part of the array you want to change. Then open the file with w+ so that it's emptied and you start at the beginning, and rewrite the contents including what you changed.
$file = file("Path To File");
$count = 1;
$maxval = count($file);
while ( $count <= $maxval ){
if ( ereg("Find this on a line",$fileї$count]) ){
$fileї$count] = "Change the line to this";
}
$count++;
}
//
// to write to the file
//
$a1 = fopen("Path to file", "w+");
flock($a1,2);
foreach ($file as $key){
$fw = fwrite($a1, $key);
}
fclose($a1);