ereg_replace help :(

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!

Moderator: General Moderators

Post Reply
MAsKrA
Forum Newbie
Posts: 14
Joined: Wed Aug 14, 2002 3:17 am
Location: Orl FL

ereg_replace help :(

Post 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);
lc
Forum Contributor
Posts: 188
Joined: Tue Apr 23, 2002 6:45 pm
Location: Netherlands

Post 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.
MAsKrA
Forum Newbie
Posts: 14
Joined: Wed Aug 14, 2002 3:17 am
Location: Orl FL

Post 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:
Post Reply