Execute PHP code in line without Eval

A "simple" class of templates is being developed, the problem is, how can I execute PHP code inside a string without using eval?

The following example: 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 do not want to use eval, because how slow and bad it should be, is there any other way to do this? The laravel blade engine does not use eval, so it should be.

Thanks,

Joel

+4
source share
2 answers

You do not need to execute PHP code. You are replacing your {{ $user }} with PHP code that is no longer running. Thus, your HTML will look like this after replacing:

 <?php echo "Dave" ?> 

Your browser believes that <?...> is an HTML tag and therefore does not display the correct name.

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

0
source

I suggest that when you assign a value to a variable, you should put it in a global variable as follows:

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

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

in this case you do not need to use evel

-one
source

Source: https://habr.com/ru/post/1496363/


All Articles