Jump to content

Help needed with variables in string.


impfut

Recommended Posts

Hi, I'm fairly new to PHP and need a bit of assistance from a wiser person please.

 

I am trying to build a simple template/tag system and have a problem retrieving the variables from a modified string. Please can someone show me the light? It's driving me crazy.

 

What I want it to output: ... Hello Susan. Your account number is 123.

What it currently outputs: .. Hello $memberName. Your account number is $memberAccount.

 

<?php
$memberName = "Susan";
$memberAccount = "123";
$content = "Hello [memberName]. Your account number is [memberAccount].";

function replaceTag($string) {
$search = array('[', ']');
$replace = array('$', '');
return (string)str_replace($search, $replace, $string);
}
$statement = replaceTag($content);
echo "$statement";
?>

 

Really struggling with this :(

 

Cheers

Dave

Link to comment
https://forums.phpfreaks.com/topic/201352-help-needed-with-variables-in-string/
Share on other sites

Try this

<?php
function replaceTag($string, $vars) {
foreach($vars as $tag => $value) {
	$string = str_replace('['.$tag.']',$value, $string);
}
return $string;
}
$vars 	  = array('memberName' => 'Susan', 'memberAccount' => '123');
$content   = "Hello [memberName]. Your account number is [memberAccount].";
$statement = replaceTag($content, $vars);
echo $statement;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.