替换单个变量工作,如何替换标记的每个出现?

时间:2016-11-08 01:08:41

标签: php mysql template-engine

所以我为我公司正在开发的项目制作了一个基本的模板系统。目前,我可以加载模板并将其打印出来,并使用我们开发的标签通过调用主模板中的<template::>template_name<::/template>来调用另一个模板中的模板。只要我只调用一个模板,这就太棒了。在第一次出现模板标签后,系统停止并且不会继续从数据库中读取其余字符串以获得其他模板标签。

如果我在脚本中多次调用SAME模板,它将向右渲染,但如果我调用一个新模板,它将被系统忽略并打印为普通文本。

这是我当前调用标签并替换它们的函数:

$inject_template = $this->get_template_name_between($template, "<template::>", "<::/template>");
if(!empty($inject_template)) {
    $query_for_template = "SELECT * FROM ".$field." WHERE templateid = '".$inject_template."' LIMIT 1";
    $injected_template_data = $wms->function->query($query_for_template);
    while($returned = mysql_fetch_array($injected_template_data)) {
        $type = $returned['templatetype'];
    }
    $template = str_replace('<template::>'.$inject_template.'<::/template>', $this->injectTemplate($inject_template, $type), $template);
}

public function injectTemplate($template_id, $template_number_type) {
    return $this->extract_template($template_id, $template_number_type);
}

public function get_template_name_between($string, $start, $end) {
    $ini = strpos($string, $start);
    if($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

请记住,如果我调用ONE标签,这是有效的,我只需要一种方法来强制该函数用每个标签替换所有标签。我想也许是一个for循环,并且计算,但不确定正确的语法来做到这一点,我一直在盯着这一整天现在大声笑。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用一直循环,直到字符串中没有模板为止。

while ($inject_template = $this->get_template_name_between($template, "<template::>", "<::/template>")) {
    $query_for_template = "SELECT * FROM ".$field." WHERE templateid = '".$inject_template."' LIMIT 1";
    $injected_template_data = $wms->function->query($query_for_template);
    $returned = mysql_fetch_array($injected_template_data);
    $type = $returned ? $returned['templatetype'] : '';
    $template = str_replace('<template::>'.$inject_template.'<::/template>', $this->injectTemplate($inject_template, $type), $template);
}

您不需要在while()周围使用mysql_fetch_array()循环,因为查询仅限于1行。

顺便说一下,你应该停止使用mysql_*功能。转换为mysqliPDO,并使用准备好的查询。

相关问题