PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How to use backreference in preg_replace() as object property?

 November 19, 2022     object, php, preg-replace, regex     No comments   

Issue

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?


Solution

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


Answered By - mickmackusa
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing