Citizen SP
Citizen SP

Reputation: 1411

Foreach template tag in php

I made the following code to replace template tags. It works fine for 1 item, but I am looking for a solution to replace every item listed. The code only replaces the template tags with the content of item 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);

Upvotes: 0

Views: 122

Answers (2)

krishna
krishna

Reputation: 4089

change this

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

to

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

echo $template;

DEMO

Upvotes: 0

Tobias Golbs
Tobias Golbs

Reputation: 4616

This should do the trick:

$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);
}

Upvotes: 1

Related Questions