Skip to content
Advertisement

The replace function doesn’t work for multi-replace

I have to change in a text file 6 different lines with 6 different words but the function str_replace doesn’t work. Why?

                    $prendo_link_per_replace = "ex.txt";                
                    $uno = "1";
                    $due = "2";
                    $tre = "3";
                    $quattro = "4";
                    $cinque = "5";
                    $sei = "6";
                    $testofile = file_get_contents($prendo_link_per_replace);
                    $testofile = str_replace($uno, $due, $testofile);
                    $testofile = str_replace($due, $tre, $testofile);
                    $testofile = str_replace($tre, $quattro, $testofile);
                    $testofile = str_replace($quattro, $cinque, $testofile);
                    file_put_contents($prendo_link_per_replace, $testofile);

I have 2 files:

  • check.php
  • text.txt

in text.php there’s:

1
2
3
4
5
6

The previous code, that I have posted, will replace the number 1,2,3,4 with the next number (2,3,4,5) but the output is only 5 for all lines. I have tried with a loop or fflush() or fwrite() or unset() but the output doesn’t change. After run the code, my page text.txt change into:

5
5
5
5
5
6

Why? Any suggestions?
I’m in a Amazon Linux Ami 2 but everywhere doesn’t work.

The true problem is that I cannot do more than one str_replace. How can I fix?

Advertisement

Answer

If this is your input file:

1
2
3
4

You could try to replace in the opposite order, e.g.:

$file_name = "ex.txt";
$file_content = file_get_contents($file_name);
$one = "1";
$two = "2";
$three = "3";
$four = "4";
$five = "5";
$file_content = str_replace($four, $five, $file_content);
$file_content = str_replace($three, $four, $file_content);
$file_content = str_replace($two, $three, $file_content);
$file_content = str_replace($one, $two, $file_content);
file_put_contents($file_name, $file_content);

Your output file will be:

2
3
4
5

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement