Jump to content

[Solved]Any Function To Get Variable Value By It's String Name?


rain13

Recommended Posts

I have html template where I want to keep $Variable in html file. I am wondering if there is any change to replace $Variable in html template with value of $Variable. So far i've looked into eval() but it didn't help. I Also tried to write dynamic code with eval and str_replace() but it didn't work

$str = '{%$abc["def"]%}';$abc["def"] = "bb";$search = '$abc["def"]';echo(eval('str_replace($search, $abc["def"] ,$str );'));

If anyone has idea about how to replace all PHP variable names in HTML template with they're values dynamically let me know. It would save a lot time if I dont have to write 1 str_replace() call for every variable.

Link to comment
Share on other sites

If you're going to put PHP identifiers in the file, then might as well just include PHP tags and echo statements also. Then you can just include the file. Otherwise you need to parse the file like PHP does to look for identifiers. With enough rules you may also be able to add slashes to escape quotes and other slashes and use eval to assign the string to a variable, which will do variable replacement.

Link to comment
Share on other sites

Here's code I made. Let me know what you guys think of it. If you got any suggestions about how it could be better let me know.

<?php$subject = 'text {%$var%} and array {%$array["key"]%} !'."\n";$var = "value";$array["key"] = "key value";echo StingReplaceFile($subject); function StingReplaceFile($string){	$pattern = '/\{\%([\$\w\[\]\"\"\/\.]+)\%\}/s'; 	preg_match_all($pattern, $string, $matches); 	foreach ($matches[0] as $key => $match) {		$SquareBracket = strpos($matches[1][$key],"["); 		if ($SquareBracket) {		$cmd = 'global '.StringLeft($matches[1][$key],$SquareBracket).'; $data = '.$matches[1][$key].';';}		else{$cmd = 'global '.$matches[1][$key].'; $data = '.$matches[1][$key].';';} 		eval ($cmd);		$string = str_replace("{%".$matches[1][$key]."%}",$data,$string);	} 	return $string;} function StringLeft($sString,$iCount){	return substr ( $sString ,0, $iCount );} ?>

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...