If you don't want to use a template engine for this task, I could suggest the following code to add to your 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;
Why using preg_replace()
?
It's known that preg_replace()
does a better job at replacing in a bigger text content rather than str_replace()
which starts to be slower and slower after each replacement (you can find a benchmark on Google, I can't seem to find it right now)
Later edit:
I found am improvement on this one.
<?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;
I have also done a little test against the str_replace()
solution. str_replace()
is faster only when there are a couple of variables (2-3). With 6 variables preg_replace()
is 2 times faster.
Here are my results:
preg_replace() 10000 times: 0.038811922073364seconds
str_replace() 10000 times: 0.085460901260376seconds
This is the code I ran to test the speed:
<?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>';