2017-03-05 85 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