2017-03-05 87 views
0

我基本上有一个模板系统,它读取模板文件,如果它具有{$ 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 SOOO是的,这只是打印The variable result is: {$test}而不是The variable result is: This is a test

如果你没有得到我的观点,然后就告诉我的评论,我会尽力解释好,困:d

回答

1

你鸵鸟政策需要使用eval此:

的以下也将做的工作:

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

这是如何工作的: preg_match_all创建了整个比赛和组数组:

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

第一个数组包含要替换的字符串,第二个变量名称必须重新将该字符串重新分隔。

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

给出了当前变量的名称。

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

替换$匹配的变量的名称值,存储在$代表(see here)。

编辑

我加入了ungreedy modifier的正则表达式,在其他情况下,它不会蒙山在同一文件的多个匹配正常工作..

+0

我需要这几乎没有什么,谢谢答案,非常感谢。 – roun512