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

Link to comment
Share on other sites

Oh, you should first open the file and read it's contents, then clear it, then change the line from variable you read the contents into and then write new edited content back.

I dont think its possible to edit single line from flatfile.

Link to comment
Share on other sites

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?

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.