inspireddesign Posted January 28, 2010 Share Posted January 28, 2010 Hello all, My problem is this: I have a function that loops through some html code and replaces any KEY that has %%value%% within the html it is passed. However, for some reason the function will not operate correctly. For example: If I have the two assigned keys in the data array. One called todaysday and the other pnum. When I run the script only the last key is getting changed (PNUM)? I would like it to loop though and change all the values indicated in the html... however, if the key doesn't exits then just keep looping until the array has found all the keys and replaced them with their correct values. Not sure what I'm doing wrong. Seems simple to me. Thanks for any help on this one. $html_input = '<table><tr>td>%%TODAYSDATE%% and %%PNUM%%</tr><td></table>'; $vars = array( 'todaysdate' => $todaysDate, 'pnum' => $policyInfo->policy_num, ); $html_output = modifier($vars, $html_input); function modifier($vars, $html) { foreach($vars as $key=>$value) { $search = "%%".strtoupper($key)."%%"; $html_output = str_replace($search, $value, $html); } return $html_output; } Quote Link to comment https://forums.phpfreaks.com/topic/190146-str_replace-array-help/ Share on other sites More sharing options...
Alex Posted January 28, 2010 Share Posted January 28, 2010 You have a logic problem with your function. You're never keeping the change, so only the last replaced value is actually being kept. You can fix it by doing this: function modifier($vars, $html) { foreach($vars as $key=>$value) { $search = "%%".strtoupper($key)."%%"; $html = str_replace($search, $value, $html); } return $html; } Or alternatively: function modifier($vars, $html) { return str_replace(array_map(create_function('$x', 'return str_pad(strtoupper($x), strlen($x) + 4, "%", STR_PAD_BOTH);'), array_keys($vars)), array_values($vars), $html); } Quote Link to comment https://forums.phpfreaks.com/topic/190146-str_replace-array-help/#findComment-1003250 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.