I am trying to replace multiple parts of a string in a file with file_put_contents.
Essentially what the function does is finds a particular phrase in the file (which are in the $new and $old arrays and replaces it.
$file_path = "hello.txt";
$file_string = file_get_contents($file_path);
function replace_string_in_file($replace_old, $replace_new) {
global $file_string; global $file_path;
if(is_array($replace_old)) {
for($i = 0; $i < count($replace_old); $i++) {
$replace = str_replace($replace_old[$i], $replace_new[$i], $file_string);
file_put_contents($file_path, $replace); // overwrite
}
}
}
$old = array("hello8", "hello9"); // what to look for
$new = array("hello0", "hello3"); // what to replace with
replace_string_in_file($old, $new);
hello.txt is: hello8 hello1 hello2 hello9
Unfortunately it outputs: hello8 hello1 hello2 hello3
So it outputs only 1 change when it should have outputted 2:
hello0 hello1 hello2 hello3
That’s a single file, so why output it after every replacement? Your workflow should be
In other words, move your file_put_contents() to OUTSIDE your loop.
As well, str_replace will accept arrays for its “todo” and “replacewith” arrays. There’s no need to loop over your inputs. so basically you should have
Your main problem is that your str_replace, as you wrote it, is never using the updated string. You constantly use the same ORIGINAL string for each replacement,