Replace values from a known variable with PHP

时间:2019-04-17 02:04:24

标签: php

I have a variable in PHP that contains a template of a card I use :

$template = '
    <div class="card">
        <h1>{{CARD_TITLE}}</h1>
        {{CARD_IMAGE}}
        {{CARD_LINK}}
    </div>
';

During a foreach, I would like to replace theses {{CARD_VALUES}} by these equivalents found in the array.

So I tried:

foreach ($items as $item) {
    echo strtr($template, array('{{CARD_TITLE}}' => $item['title']));
    echo strtr($template, array('{{CARD_IMAGE}}' => $item['image']));
    echo strtr($template, array('{{CARD_LINK}}' => $item['link']));
}

But it doesn't work.

Any ideas why please ?

1 个答案:

答案 0 :(得分:1)

You're echoing the result each time you do a replacement, instead of doing all the replacements and then doing the echo. This should work:

foreach ($items as $item) {
    echo strtr($template, array('{{CARD_TITLE}}' => $item['title'],
                                '{{CARD_IMAGE}}' => $item['image'],
                                '{{CARD_LINK}}' => $item['link']));
}

Demo on 3v4l.org