解析文本文件并打印可能的变量

I basically have a template system, it reads the template file and if it has {$test}, I want it to print the actual variable $test instead of {$test}.

So how here it works in my system:

I file_get_contents($template); then I use preg_match_all with the following regexp: /{\$(.*?)}/

Now, when it finds the {$variable} in the text file, how to make it post the actual variable value? Should I use eval()?

Here is a snippet of my code:

public function ParseTemplate()
{
    // Get the file contents.
    $content = file_get_contents("index.tmp");

    // Check for variables within this template file.
    preg_match_all('/{\$(.*?)}/', $content, $matches);

    // Found matches.
    if(count($matches) != 0)
    {
        foreach ($matches[1] as $match => $variable) {
            eval("$name = {\$variable}");
            $content = str_replace($name, $name, $content);
        }
    }

    // Output the final result.
    echo $content;
}

index.tmp

The variable result is: {$test}

index.php

$test = "This is a test";
ParseTemplate();

I am a bit new to eval sooo yeah, it just prints The variable result is: {$test} instead of The variable result is: This is a test

If you didn't get my point then just tell me in a comment and I'll try to explain better, sleepy :D

You don´t need to use eval for this:

The following will also do the work:

function ParseTemplate()
{
    // Get the file contents.
    $content = 'The variable result is: {$test} and {$abc}';
    $test = 'ResulT';
    $abc = 'blub';

    // Check for variables within this template file.
    preg_match_all('/{\$(.*)}/U', $content, $matches);

    // Found matches.
    foreach ($matches[0] as $id => $match) {

        $rep = $matches[1][$id];
        $content = str_replace($match, $$rep, $content);
    }

    // Output the final result.
    echo $content;
}

ParseTemplate();

How does this works: preg_match_all creates an array with whole matches and group:

array(
    0=>array(
        0=>{$test}
        1=>{$abc}
    )
    1=>array(
        0=>test
        1=>abc
    )
)

The first array contains the strings, you want to replace, the second the variable names, which have to repace this strings.

$rep = $matches[1][$id];

gives you the name of the current variable.

$content = str_replace($match, $$rep, $content);

replaces the $match with the value of the variable with the name, that is stored in $rep (see here).

EDIT

I added the ungreedy modifier to the regex, in other case it will not work properly whith multiple matches in the same file..