2015-12-30 100 views
0

我想制作一个(模板)系统,所以我需要替换一个值的标签。该模板存储在一个名为“template.tpl”和文件包含以下内容:PHP preg_replace多次

{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

我可以建议寻找Smarty或Twig吗? – Scuzzy

+1

我想你将需要一个表示数组赋值的数组,并且可以检测为每个索引分配了什么类型的内容,以便它可以很聪明并且应用特定的模式匹配,如果说数据是数组vs字符串。例如,你如何知道 {userlist}需要迭代?假设关闭{/ userlist}意味着这个? – Scuzzy

+0

@Scuzzy我只需要这两个功能,所以我认为这比使用Smarty更快。 – LittleStack

回答

1

这里是一个开始......

这段代码背后的想法是找到{/标签} {每个标签}之间的内容和发送回通过功能,这将允许嵌套的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; 
} 
+0

嗨,谢谢!很抱歉,我答复晚了。这段代码很好用!感谢您的解释和代码。 – LittleStack

+0

你可能会在整个地方有很多多余的空白,你可以用'trim()'来包装一些代码来解决它,或者只是确保你所有使用HTML标签的格式都能做到这一点。 – Scuzzy