smith.james0 Posted March 12, 2013 Share Posted March 12, 2013 I have the following code to replace some values in a template $page_contance_before = file_get_contents('includes/contact.php'); $postname = $_SESSION['post']['name']; $postemail = $_SESSION['post']['email']; $postmessage = $_SESSION['post']['message']; $None = $_SESSION['n1']; $Ntwo = $_SESSION['n2']; $PAGE_VARScontact = array( 'NAME' => $postname, 'EMAIL' => $postemail, 'MESSAGE' => $postmessage, 'None' => $None, 'Ntwo' => $Ntwo, ); print_r($PAGE_VARScontact); foreach ($PAGE_VARScontact as $K => $V) { $page_contance = str_replace("{".$K."}",$V,$page_contance_before); echo "k $K - v $V <br />"; } The problem I have is only 'Ntwo' is being replaced, if I delete 'Ntwo' => $Ntwo, from the array, then only 'None' gets replaced. Why is it only replacing the last value in the array, I have the same code working else were in the site no problem! James Link to comment https://forums.phpfreaks.com/topic/275563-str_replace-help-needed/ Share on other sites More sharing options...
requinix Posted March 12, 2013 Share Posted March 12, 2013 $page_contance = str_replace("{".$K."}",$V,$page_contance_before);Because you keep replacing from the original string, not the one that has previous replacements. Link to comment https://forums.phpfreaks.com/topic/275563-str_replace-help-needed/#findComment-1418235 Share on other sites More sharing options...
AyKay47 Posted March 12, 2013 Share Posted March 12, 2013 A less resource intensive solution would be: $search = array("{NAME}", "{EMAIL}", "{MESSAGE}", "{none}", "{Ntwo}"); $replace = array($postname, $postemail, $postmessage, $None, $Ntwo); $page_contance = str_replace($search, $replace, $page_contance_before); Link to comment https://forums.phpfreaks.com/topic/275563-str_replace-help-needed/#findComment-1418237 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.