我想创建一个(模板)系统,所以我需要替换值的标签。模板存储在名为' template.tpl'的文件中。并包含以下内容:
{title}
{description}
{userlist}
{userid} is the id of {username}
{/userlist}
我有以下PHP脚本来重写标记:
$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);
现在我想扩展脚本,以便我可以重写{userlist}。我有以下数据包含数据:
$array = array(
1 => "Hendriks",
2 => "Peter"
);
如何创建一个返回例如以下输出的脚本?
The big user list
The big storage of all the users
1 is the id of Hendriks
2 is the id of Peter
我希望我尽可能清楚地解释它。
答案 0 :(得分:1)
这是一个开始...
这段代码背后的想法是找到每个{tag} {/ tag}之间的内容并通过函数发回它,这也允许嵌套的foreach迭代,但是没有太多的检查,例如区分大小写将是一个问题,它不会清理不匹配的标签。那是你的工作:))
$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;
}