Reputation: 68
I want to make a (template)system so I need to replace tags for a value. The template is stored in a file called 'template.tpl' and contains the following:
{title}
{description}
{userlist}
{userid} is the id of {username}
{/userlist}
I have the following PHP script to rewrite the tags:
$template = file_get_contents('template.tpl');
$template = preg_replace('/{title}/', 'The big user list', $template);
$template = preg_replace('/{description}/', 'The big storage of all the users', $template);
Now I want to expand the script so I can rewrite the {userlist}. I have the following array with data:
$array = array(
1 => "Hendriks",
2 => "Peter"
);
How can I create a script that returns for example the following output?
The big user list
The big storage of all the users
1 is the id of Hendriks
2 is the id of Peter
I hope I have explained it as clearly as possible.
Upvotes: 0
Views: 742
Reputation: 12332
Here's a start...
The idea behind this code is to find the content between each {tag}{/tag} and send it back through the function, this would permit nested foreach iteration as well, but there's not much checking eg case sensitivity will be an issue and it doesn't clean up unmatched tags. That's your job :)
$data = array();
$data['title'] = 'The Title';
$data['description'] = 'The Description';
$data['userlist'] = array(
array('userid'=>1,'username'=>'Hendriks'),
array('userid'=>2,'username'=>'Peter"')
);
$template = '{title}
{description}
{userlist}
{userid} is the id of {username} {title}
{/userlist}';
echo parse_template($template,$data);
function parse_template($template,$data)
{
// Foreach Tags (note back reference)
if(preg_match_all('%\{([a-z0-9-_]*)\}(.*?)\{/\1\}%si',$template,$matches,PREG_SET_ORDER))
{
foreach( $matches as $match )
{
if(isset($data[$match[1]]) and is_array($data[$match[1]]) === true)
{
$replacements = array();
foreach( $data[$match[1]] as $iteration )
{
$replacements[] = parse_template($match[2],$iteration);
//$replacements[] = parse_template($match[2],array_merge($data,$iteration)); // You can choose this behavior
}
$template = str_replace($match[0],implode(PHP_EOL,$replacements),$template);
}
}
}
// Individual Tags
if(preg_match_all('/\{([a-z0-9-_]*)\}/i',$template,$matches,PREG_SET_ORDER))
{
foreach( $matches as $match )
{
if(isset($data[$match[1]]))
{
$template = str_replace($match[0],$data[$match[1]],$template);
}
}
}
return $template;
}
Upvotes: 1