我基本上有一個模板系統,它讀取模板文件,如果它具有{$ 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
我需要這幾乎沒有什麼,謝謝答案,非常感謝。 – roun512