variable substitution - Problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
neds75
Forum Newbie
Posts: 3
Joined: Thu Jul 13, 2006 4:50 am

variable substitution - Problem

Post by neds75 »

Hi programmers,
I have one problem, and don't have idea how to solve it.
Here is very much simplyfied code with which I have problem:

Code: Select all

<?php
$variable = "<?php
	\$v1 = \"10\";
	\$v2 = \"50\";
	\$output = \$v1+\$v2;
	@include \"./functions.php\";//This function provde some output too
	echo \$output;
	?>";
$template = "<html>
				<head><title>Test</title></head>
				<body>
				<%variable%>
				</body>
			</html>";

$template = str_replace("<%variable%>",$variable,$template);

echo $template;
?>
The problem is when I run this script in browser I get next html code:

Code: Select all

<html>
				<head><title>Test</title></head>
				<body>
				<?php
	$v1 = "10";
	$v2 = "50";
	$output = $v1+$v2;
	@include "./functions.php";
	echo $output;
	?>
				</body>
			</html>
Of course this is totaly expected($variable is string), but I want that all php variables to be substituted with their values when I do echo $template, so I do not want any php code in browser.
I solved this problem by writing $template to file, and then called this file via class that imitate browser(snoopy), and it works as I wanted, but the problem is because I have to write to file, and that may be very slow(this is part of template engine).
SO my question is:
Is it possible to do substitutions somehow in memory, without writing template variable(or $variable) to file and accessing it via browser?

I know this is very specific problem, hope someone will have some ideas.

Thanks,
Ivica
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

neds75
Forum Newbie
Posts: 3
Joined: Thu Jul 13, 2006 4:50 am

Post by neds75 »

You are my man :)

Yes, eval works, with some additional codes, because problem with <?php tag in string.


Thank you very much.

Here is sollution, if someone need it:

Code: Select all

<?php

$variable = "<?
	\$v1 = \"10\";
	\$v2 = \"50\";
	\$output = \$v1+\$v2;
	@include \"./functions.php\";
	echo \$output;
	?>";
$template = "<html>
				<head><title>Test</title></head>
				<body>
				<%variable%>
				</body>
			</html>";

$template = str_replace("<%variable%>",$variable,$template);

//eval("\$template = \"$template\";");;
ob_start();
eval ('?>' . $template);
$template = ob_get_clean();
// Do whatever else you want with $text before outputting it
echo $template;

?>
Post Reply