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

时间:2017-03-05 11:56:23

标签: php

我基本上有一个模板系统,它读取模板文件,如果它有{$ test},我希望它打印实际变量$ test而不是{$ test}。

那么它在我的系统中是如何工作的:

file_get_contents($template);然后我使用以下正则表达式preg_match_all/{\$(.*?)}/

现在,当它在文本文件中找到{$variable}时,如何使其发布实际变量值?我应该使用eval()吗?

以下是我的代码片段:

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();

我对eval有点新鲜,所以是的,只是打印The variable result is: {$test}而不是The variable result is: This is a test

如果您没有明白我的观点,那么请在评论中告诉我,我会尝试更好地解释,困倦:D

1 个答案:

答案 0 :(得分:1)

您不需要使用eval:

以下也将开展工作:

.remove()

这是如何运作的: preg_match_all创建一个包含完整匹配和组的数组:

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();

第一个数组包含要替换的字符串,第二个数组包含必须重新命名此字符串的变量名。

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

为您提供当前变量的名称。

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

将$ match替换为带有名称的变量值,该名称存储在$ rep(see here)中。

修改

我将ungreedy modifier添加到正则表达式中,在其他情况下,它会在同一个文件中多次匹配时无效。