开发者

Overwrite Content in PHP fwrite()

开发者 https://www.devze.com 2022-12-30 21:13 出处:网络
Is there any way you can overwrite a line in PHP. let me be a little more clearer using examples. My array

Is there any way you can overwrite a line in PHP. let me be a little more clearer using examples.

My array

array{
    [DEVICE] => eth0,
    [IPADDR] => 192.168.0.2,
    [NETMASK] => 255.255.255.0,
    [NETWORK] => 192.168.0.0,
    [BROADCAST] => 255.255.255.255,
    [GATEWAY] => 192.168.0.1,
    [ONBOOT] => no
}

File im overwriting

DEVICE=eth0
IPADDR=192.168.200.2
NETMASK=255.255.255.0
NETWORK=192.168.200.0
BROADCAST=255.255.255.255
GATEWAY=192.168.200.1
ONBOOT=no
DNS1=195.100.10.1

Result of the File that is rewritten

DEVICE=eth0
IPADDR=192.168.0.2
NETMASK=255.255.255.0
NETWORK=192.168.0.0
开发者_如何转开发BROADCAST=255.255.255.255
GATEWAY=192.168.0.1
ONBOOT=no
DNS1=195.100.10.1

Note that DNS1=195.100.10.1 Stays in the file becuase it dosent have a key with the value of DNS in our array.

Thanks


You need to find an algorithm to do it :

  1. Read the file to overwrite with the file() function (look carefully at the options, you don't want the news line char to be included in the array).
  2. Loop through the array and explode() each element to create a new key => value array.
  3. Merge the obtained array with your first array.
  4. Implode back each items of the new array
  5. Overwrite the file by imploding the array with \n


I've done it before by reading the whole file in a variable and then using preg_replace to replace the various variables I wanted to change.


I'll second webbiedave's comment. You could only seek into the appropriate position and then use fwrite if the what you were writing over had the same size of what you're writing (it's not the case).

0

精彩评论

暂无评论...
验证码 换一张
取 消