Reputation: 49
Sample contacts.txt file:
doe, john, 123
smith, jane, 456
etc
etc
etc
If I want to overwrite smith, jane, 456
with cooper, jones, 678
with $handle = fopen("contacts.txt", "w");
How come it removes all the lines before and after smith, jane, 456
Upvotes: 0
Views: 383
Reputation: 79024
fopen()
may not be the best choice, especially with w
:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
For reasonably sized files this should do it:
$data = file_get_contents('contacts.txt');
$data = str_replace('smith, jane, 456', 'cooper, jones, 678', $data);
file_put_contents('contacts.txt', $data, LOCK_EX);
Upvotes: 2