Jump to content

Replacing specified line in file.


wwfc_barmy_army

Recommended Posts

Hello Guys.

 

I have this PHP code to get a line from a file that starts with the word 'Number'. There is only 1 line with this in:

while( ! feof($file))
{
    $line = fgets($file);
    if (preg_match("/^Number\b/", $line))
    {
        echo $line;
    }
}

 

How would I go about replacing just that line? Any suggestions?

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/198915-replacing-specified-line-in-file/
Share on other sites

I didn't include the whole code and it may change your answer:

 

$file = fopen("myfile","r");
while( ! feof($file))
{
    $line = fgets($file);
    if (preg_match("/^Number\b/", $line))
    {
        echo $line;
    }
}
fclose($file);

 

If i'm not mistaken it's opening it with read access, so I don't think that would work.

 

Any other ideas?

 

Thanks.

Just a passing thought (PSUEDO code)...

 

$lines = file($file_name);
$rows = count($lines);
$needle = "Number";
$new_content = "Whatever";
$i = 0;
while($i<$rows) {
if $needle in $line[$i];
   $line[$i] = $new_content;
$i = $rows;
}
$i ++;
}
write the $lines array back to a file

 

make sense?

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.