【问题标题】:Replacing a single varible works, how do I replace every occurance of a tag?替换单个变量有效,如何替换每次出现的标签?
【发布时间】:2016-11-08 01:08:40
【问题描述】:

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

如果我在脚本中多次调用 SAME 模板,它将正确呈现,但如果我调用 NEW 模板,它会被系统忽略并打印为普通文本。

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

$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 循环,并在计数,但不确定执行此操作的正确语法,我现在整天都在盯着这个,哈哈。提前致谢!

【问题讨论】:

  • 尝试使用preg_replace_callback()。它将替换正则表达式的所有匹配项,您可以提供一个回调函数,根据模板名称查找替换项。

标签: php mysql template-engine


【解决方案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);
}

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

顺便说一句,您应该停止使用mysql_* 函数。转换为mysqliPDO,并使用准备好的查询。

【讨论】:

  • 非常感谢。这完美地解决了这个问题。我正在使用mysql_* 函数,因为它具有向后兼容性,并且开发服务器没有在 php 或 mysql 上运行最新版本,我们将研究切换.. 谢谢
  • mysqli 适用于 PHP 5.0.7 和更新版本。 PDO 带有 PHP 5.1 和更新版本。向后兼容性应该不是问题。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2020-06-08
  • 2012-03-13
  • 2018-09-08
  • 1970-01-01
相关资源
最近更新 更多