简体   繁体   中英

Execute PHP code in a String without Eval

Currently developing a "simple" template class, the problem is how would I execute PHP code within a string without using eval?

A following example is how my template class works:

$user = 'Dave';

ob_start();     
include 'index.tpl';
$content = ob_get_clean(); // String

$pattern = sprintf('/%s\s*(.+?)\s*%s/s', '{{', '}}'); // replace with php tags
$new_content = preg_replace($pattern, '<?php echo $1; ?>', $content);

echo $new_content; 

index.tpl

<html>
     <head></head>
     <body>
         Hello {{ $user }}!
     </body>
</html>

I get the following result:

Hello !

I don't want to use eval because how slow and bad it is to use, is there any other way of doing this? laravel blade engine does not use eval so there must be.

Thanks,

Joel.

You don't need to execute PHP Code. You replace your {{ $user }} with PHP code, which doesn't get executed anymore. So your HTML will look like this after the replace:

<?php echo "Dave" ?>

Your Browser thinks <?...> is an HTML-tag and thus doesn't display the correct name.

Solution: Just replace {{ $user }} with Dave , why do you want to add more PHP Code?

I suggest to you when you assign a value to a variable, you should put it as a global variable like this;

$GLOBALS['My_Vars']['VarName'] = $Value;

when you retrevie the name of the variable from your code which is in your example $user, you change {{ $user }} to the value within $GLOBALS['My_Vars']['user']

in this case you don't need to use evel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM