Php – Super Basic Templating System

phptemplates

I'd like to be able to replace things in a file with a regular expression using the following scheme:

I have an array:

$data = array(
  'title' => 'My Cool Title',
  'content' => ''
)

I also have a template (for clarity's sake, we'll assume the below is assigned to a variable $template)

<html>
<title><% title %></title>
<body><% content %></body>
</html>

I'd like to be able to use one regular expression to do the whole thing, so it can be as general as possible; The following is my stab at it (which doesn't work)

$endMarkup = preg_replace('/<% ([a-z]+) %>/',$data["\\1"], $template);

Is there a clean solution for putting associative array data into a template by array index?

Best Solution

With a little work before hand you can do it with a single preg_replace call:

$replacements = array();
foreach ($data as $search => $replacement) {
   $replacements["/<% $search %>/"] = $replacement;
}
$endMarkup = preg_replace(
     array_keys($replacements), 
     array_values($replacements), 
     $template);
Related Question