如果你不想使用模板引擎這個任務,我可以建議將下面的代碼添加到您的index.php:
<?php
$var1 = 'text';
$templateVars = array('var' => $var1);
$content = file_get_contents('file.html');
foreach($templateVars as $tplVar => $tplVarContent) {
$content = preg_replace('/\{' . $tplVar . '\}/', $tplVarContent, $content);
}
echo $content;
爲什麼使用preg_replace()
?
據瞭解,preg_replace()
在更換一個更大的文本內容,而不是str_replace()
它開始是每次更換後慢做一個更好的工作(你可以找到關於谷歌的標杆,我似乎無法找到它現在)
後來編輯:
我發現這個上午一點改進。
<?php
$var1 = 'test';
$templateVars = array('var' => $var1);
$content = file_get_contents('tpl.tpl');
$content = preg_replace('/\{([a-zA-Z0-9_]+)\}/e', "\$templateVars['\\1']", $content);
echo $content;
我也對str_replace()
解決方案做了一些測試。 str_replace()
是更快只有當有幾個變量(2-3)。有6個變量preg_replace()
是快2倍。
這裏是我的結果:
preg_replace() 10000 times: 0.038811922073364seconds
str_replace() 10000 times: 0.085460901260376seconds
這是我跑測試速度的代碼:
<?php
$var1 = 'text';
$templateVars = array('var' => $var1, 'var1' => 'blabla', 'var3' => 'variable3', 'var22' => $var1, 'var133' => 'blabla', 'var3444' => 'variable3');
$content = file_get_contents('tpl.tpl');
$start = microtime(true);
for($i = 0; $i <= 9999; $i++)
{
$content = preg_replace('/\{([a-zA-Z0-9_]+)\}/e', "\$templateVars['\\1']", $content);
}
$end = microtime(true);
echo 'preg_replace() '. $i . ' times: ' . ($end - $start) . 'seconds<br>';
$start = microtime(true);
for($i = 0; $i <= 9999; $i++)
{
foreach($templateVars as $tplVar => $tplVarContent) {
$content = str_replace('{' . $tplVar . '}', $tplVarContent, $content);
}
}
$end = microtime(true);
echo 'str_replace() '. $i . ' times: ' . ($end - $start) . 'seconds<br>';
你可以通過一些模板引擎例如Smarty。他們如何做,並可以使用模板引擎。他們已經爲你做了 – 2011-03-31 12:27:40