Skip to content
Advertisement

Search a file for a string and replace everything after a character in that line

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement