Reputation: 460
I am looking to use PHP to open a file (see example below), search it line by line for a string $colour
and replace everything after the =
with $value
.
file.txt before:
red=0
green=23
blue=999
yellow=44
If my $value
is "1"
and my colour is "blue"
, my file should change to:
red=0
green=23
blue=1
yellow=44
My code so far is:
function write($colour, $value) {
$file = 'path';
$file_contents = file_get_contents($file);
$file_contents = str_replace($colour, $value, $file_contents);
file_put_contents($file, $file_contents);
}
However this only gets as far as replacing the $colour
with the $value
(not everything after the "=") see below my output:
red=0
green=23
1=999
yellow=44
How do I do this?
Upvotes: 0
Views: 281
Reputation: 1319
This happens because your code only replaces color with value specified. To do this you would have to load file line by line, explode by = to have color and value separetely, adjust and store again. Or use regexes.
I would like to propose different approach. Instead on operating on file loaded as string, load file as array. There is a function for this: parse_ini_file.
<?php
// load the file to array with elements key => value
$data = parse_ini_file('conf.txt');
var_dump($data);
// change the data in array however you want - here i add 1 to red everytime this script is called, but it can be whatever: $data['red'] = 2; or similar
$data['red']++;
// now just build the contents of the file again and save it
$contents = '';
foreach ($data as $key => $value) {
$contents .= $key.'='.$value.PHP_EOL;
}
file_put_contents('conf.txt', $contents);
Result:
// this is how the file looks like at start
cat conf.txt
red=0
green=23
blue=1
yellow=44
// this is how $data looks
array(4) {
["red"]=>
string(1) "0"
["green"]=>
string(2) "23"
["blue"]=>
string(1) "1"
["yellow"]=>
string(2) "44"
}
// and the file after the execution
cat conf.txt
red=1
green=23
blue=1
yellow=44
Change $data['red']++;
to $data[$color] = $value;
put it into a function and thats it.
Upvotes: 1
Reputation: 57121
The problem is that you are just replacing the text of the colour with the value in
$file_contents = str_replace($colour, $value, $file_contents);
this doesn't replace the full line though.
Using preg_replace()
, you can replace something starting with the colour followed by and =
till the end of line with...
$file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);
Upvotes: 1