PHP 将数组中的值替换为 HTML 字符串


PHP Replace values in an array into an HTML string

听起来很简单,但我今天感觉很愚蠢。

如果我有这样的数组:

$defined_vars = array(
    '{POST_TITLE}' => $item['post']['name'], 
    '{POST_LINK}' => $item['post']['link'], 
    '{TOPIC_TITLE}' => $item['topic']['name'], 
    '{TOPIC_LINK}' => $item['topic']['link'], 
    '{MEMBERNAME}' => $txt['by'] . ' <strong>' . $item['membername'] . '</strong>', 
    '{POST_TIME}' => $item['time'], 
    '{VIEWS}' => $txt['attach_viewed'] . ' ' . $item['file']['downloads'] . ' ' . $txt['attach_times'],
    '{FILENAME}' => $item['file']['name'],
    '{FILENAME_LINK}' => '<a href="' . $item['file']['href'] . '">' . $item['file']['name'] . '</a>',
    '{FILESIZE}' => $item['file']['size'],
    '{DIMENSIONS}' => $item['file']['image']['width'] 'x' $item['file']['image']['height'],
);

还有一个像这样的字符串:

$string = '<div class="largetext centertext">{POST_LINK}</div><div class="smalltext centertext">{MEMBERNAME}</div><div class="floatright smalltext dp_paddingright">{POST_TIME}</div><div class="dp_paddingleft smalltext">{VIEWS}</div>';

我需要将其替换为这些键的值。 这可能做到吗? 也许以某种方式使用str_replace()? 数组键中是否允许有大括号? 这会导致任何问题吗? 此外,我需要它来替换找到这些的所有时间的$string值,因为可能需要超过 1 次的相同输出。 例如,如果{POST_TITLE}被定义两次,它应该在字符串中使用它的位置输出两次该值。

谢谢

str_replace支持数组。以下语法将做到这一点。

$string=str_replace(array_keys($defined_vars), array_values($defined_vars), $string);
大括号在数组键中受支持,

因为它在字符串中,字符串作为数组 yes 受支持。

foreach($defined_vars as $key=>$value) {
  $string = str_replace($key,$value,$string);
}

这是像您要求的那样使用str_replace,很容易看到正在发生的事情。 Php 还具有 strtr 或字符串翻译函数来做到这一点,因此您也可以使用

$string = strtr($string,$defined_vars);

但必须记住该函数的作用。

是的,你的str_replace是合适的,只是foreach()循环你的数组

if(isset($defined_vars) and is_array($defined_vars))
{
  foreach($defined_vars as $token => $replacement)
  {
    $string = str_replace($token,$replacement,$string);
  }
}

您可能希望对变量应用一些过滤器,以确保您的 HTML 不会损坏。

<div class="largetext centertext">
  <a href="<?=$item['post']['link']?>"><?=$item['post']['title']?></a>
</div>
<div class="smalltext centertext">
  <?=$txt['by']?><strong><?$item['membername']?></strong>
</div>
<div class="floatright smalltext dp_paddingright"><?$item['time']?></div>
<div class="dp_paddingleft smalltext">
  <?=$txt['attach_viewed']?>
  <?=$item['file']['downloads']?>
  <?=$txt['attach_times']?>
</div>

好吧,如果它是一个用户定义的字符串,你必须替换

$string = strtr($string,$defined_vars);

另外,我希望您过滤掉用户编辑的HTML,以防止他们窃取您的cookie并以管理员或任何其他用户的身份登录。