Jump to content

str_replace Array help.


inspireddesign

Recommended Posts

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;
    }

Link to comment
Share on other sites

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);
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.