Home > Enterprise >  How to use backreference in preg_replace() as object property?
How to use backreference in preg_replace() as object property?

Time:11-09

I have the following PHP code:

$items = json_decode('[
    {"title":"Title #1", "text":"Text #1"},
    {"title":"Title #2", "text":"Text #2"}
]');

$itemTmpl = "<h3 class='foo'>{title}</h3><div class='bar'>{text}</div>";

$html = [];
foreach($items as $item) {
    $html[] = preg_replace("/\{[a-z] \}/", $item->{$1}, $itemTmpl);
}
    
echo implode("\n", $html);

As you see, I'm trying to use backreference as object property in order to replace variables like {title} and {text} with data from the array expecting $item->{'title'} and $item->{'text'}.

But the current code throws the error

syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in ...

How to resolve the issue?

CodePudding user response:

There will be several ways to do this; I'll demonstrate just one way.

  1. iterate over your decoded items,
  2. Replace each placeholder by accessing the key of the given item using the text captured from between the curly braces

Code: (Demo)

$html = [];
foreach ($items as $item) {
    $html[] = preg_replace_callback(
        '/{([a-z] )}/',
        fn($m) => $item->{$m[1]},
        $itemTmpl
    );
}
var_export($html);
  • Related