Page 1 of 1

ereg_replace help :(

Posted: Wed Sep 04, 2002 3:19 am
by MAsKrA
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 :twisted:

Code: Select all

$fp = fopen ("$htaccess", "aw");
        $fcontents = file ("$htaccess");   
        foreach($fcontents as $value){  
        if(ereg("Counterfile (.*)", $value, $matches)){  
        echo $matchesї1];                
        $replace = ereg_replace( "Counterfile $matchesї1]","$counter_syntax\n","$fcontents"); 
        }  
        }  

        //
        // close the file
        //
        fclose($fp);

Posted: Wed Sep 04, 2002 9:34 am
by lc
Ok lemme see:

I think that this might work.

Code: Select all

$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.

Posted: Fri Sep 06, 2002 5:17 am
by MAsKrA
Thank you,

You send me in the right direction tho I had to make some small changes to your suggestion.

Code: Select all

$file = file("Path To File");
        $count = 1;
        $maxval = count($file);
        while ( $count <= $maxval )&#123;
        if ( ereg("Find this on a line",$file&#1111;$count]) )&#123;
        $file&#1111;$count] = "Change the line to this";
        &#125;
        $count++;
        &#125;

        //
        // to write to the file
        //

        $a1 = fopen("Path to file", "w+");
        flock($a1,2);
        foreach ($file as $key)&#123;
        $fw = fwrite($a1, $key);
        &#125;
        fclose($a1);
Again thanks :twisted: