在PHP的Foreach模板标记

时间:2014-03-03 12:52:51

标签: php regex preg-match

我制作了以下代码来替换模板标签。它适用于1个项目,但我正在寻找一个解决方案来替换列出的每个项目。该代码仅使用第2项的内容替换模板标记。

$template = '
<div style="border:1px solid blue;padding:10px;">
<h1>[item_title]</h1>
<p>[item_text]</p>
<a href="[item_link]">[item_link]</a>
</div>

<div style="border:1px solid blue;padding:10px;">
<h1>[item_title]</h1>
<p>[item_text]</p>
<a href="[item_link]">[item_link]</a>
</div>
';

/// ITEM 1 
$title   = 'title 1';
$text    = 'text text text';
$link    = 'http://www.google.com';

/// ITEM 2 
$title   = 'title 2';
$text    = 'text2 text2 text2';
$link    = 'http://www.google.com';

$regex = array(
'/\[\item_title\]/is' => $title,
'/\[\item_text\]/is' => $text,
'/\[\item_link\]/is' => $link,
);


echo preg_replace(array_keys($regex), array_values($regex), $template);

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

$template = '<div style="border:1px solid blue;padding:10px;"><h1>[item_title]</h1><p>[item_text]</p><a href="[item_link]">[item_link]</a></div>';

$items = array(
    array(
        "title" => "title 1",
        "text" => "text text text",
        "link" => "http://www.google.com",
    ),
    array(
        "title" => "title 2",
        "text" => "text text text",
        "link" => "http://www.google.com",
    )
);
foreach($items as $item) {
    $regex = array(
        '/\[\item_title\]/is' => $item["title"],
        '/\[\item_text\]/is' => $item["text"],
        '/\[\item_link\]/is' => $item["link"],
    );
    echo preg_replace(array_keys($regex), array_values($regex), $template);
}

答案 1 :(得分:0)

更改此

echo preg_replace(array_keys($regex), array_values($regex), $template);

foreach($regex as $keys => $values)
{
    $template = preg_replace($keys, $values, $template);
}

echo $template;

DEMO