impfut Posted May 11, 2010 Share Posted May 11, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/201352-help-needed-with-variables-in-string/ Share on other sites More sharing options...
JonnoTheDev Posted May 11, 2010 Share Posted May 11, 2010 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; ?> Quote Link to comment https://forums.phpfreaks.com/topic/201352-help-needed-with-variables-in-string/#findComment-1056380 Share on other sites More sharing options...
impfut Posted May 11, 2010 Author Share Posted May 11, 2010 Works like a charm! Thank you very much chap! Quote Link to comment https://forums.phpfreaks.com/topic/201352-help-needed-with-variables-in-string/#findComment-1056392 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.