Lorenz Meyer Lorenz Meyer - 1 year ago 139
PHP Question

How to expand variables in a string


I'd like to expand variables in a string in the same manner that variable in a double quoted string get expanded.

$string = '<p>It took $replace s</>';
$replace = 40;

should become
'<p>It took 40 s</>';

I see a obvious solution like this:

$string = str_replace('"', '\"', $string);
eval('$string = "$string";');

But I really don't like it, because eval() is insecure. Is there any other way to do this ?


I'm building a simple templateing engine, that's where I need this.

Example Template (view_file.php)


Template rendering (simplified code):

$params = array('title' => ...);

function render($view_file, $params)
$text = ob_get_contents();
expression_i_look_for; // this will expand the variables in the template
return $text;

The expansion of the variables in the template simplifies it's syntax. Without it, the above example template would be:

<h1><?php echo $title;?></h1>
<p><?php echo $content;?></p>

Do you think this approach is good ? Or should I look in another direction ?


Finally I understand that there is no simple solution due to flexible way PHP expands variables (even
would be valid.

So there are only two options:

  1. Adopt an existing full fledged templating system

  2. Stick with something very basic that essentially is limited to including the view files via

Answer Source

I would rather suggest using some existing template engines, like for example Smarty, but if you really want to do it by yourself you can use the simple regular expression to match all variables constructed with for example letters and numbers and then replace them with correct variables:


$text = 'hello $world, what is the $matter? I like $world!';


$world = 'World';
$matter = 'matter';

foreach(array_unique($out[1]) as $variable){
    $text=str_replace('$'.$variable, $$variable, $text);

echo $text;



hello World, what is the matter? I like World!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download