PHP Search and replace multiple files, multiple instances

79 views Asked by At

I am trying to write a php script that will change multiple instances of words/phrases in multiple files

I have a form that collects the variables

Here's my script

$introname= $_POST['introname'] ;
$introid= $_POST['introid'] ;
$officeid= $_POST['officeid'] ;
$introname= $_POST['introname'] ;
$office= $_POST['office'] ;
$email= $_POST['email'] ;


$q="intrologin.php";
$f=fopen($q,'r');
$c=fread($f,10000);
$final = str_replace("jojointroname", $_POST['introname'], $c);
$final = str_replace("jojointroid", $_POST['introid'], $c);
$final = str_replace("jojoofficeid", $_POST['officeid'], $c);
$final = str_replace("jojooffice", $_POST['office'], $c);
fclose($f);
$f=fopen($q,'w');
fwrite($f,$final);
fclose($f);


$p="introprocessing.php";
$f=fopen($p,'r');
$c=fread($f,10000);
$final = str_replace("jojoemail", $_POST['email'], $c);
fclose($f);
$f=fopen($p,'w');
fwrite($f,$final);
fclose($f);

When I run this, the second part of the script runs fine and changes the email, but the first part of the script only changes 'office', not the preceding 3 variables.

Do I need to create a separate group for each change or am I missing something?

1

There are 1 answers

1
Mic Jaw On

It is because each time you call str_replace you give it the original string $c so when you assign that to $final it overwrites the previous change. This should work:

$final = str_replace("jojointroname", $_POST['introname'], $c);
$final = str_replace("jojointroid", $_POST['introid'], $final);
$final = str_replace("jojoofficeid", $_POST['officeid'], $final);
$final = str_replace("jojooffice", $_POST['office'], $final);