user1631995
user1631995

Reputation:

Multiple file_put_contents with with str_replace?

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

Upvotes: 0

Views: 1126

Answers (2)

Marc B
Marc B

Reputation: 360882

That's a single file, so why output it after every replacement? Your workflow should be

a) read in file
b) do all replacements
c) write out modified file

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

$old = array(...);
$new = array(...);

$text = file_get_contents(...);
$modified = str_replace($old, $new, $text);
file_put_contents($modified, ....);

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,

$replace = str_replace($replace_old[$i], $replace_new[$i], $file_string); 
                                                            ^^^^^^^^^^^---should be $replace

Upvotes: 4

Alex Howansky
Alex Howansky

Reputation: 53646

You're not updating $file_string with each iteration. I.e., you set it once at the start of the loop, replace the first pair, and then the second call to replace uses the original $file_string again.

Upvotes: 0

Related Questions