0

I want to use html as a template and filling the data with PHP. If I've some html this way

<h1>${heading-1}</h1>
<p>${paragraph}</p>

I want to replace the template tags with the matching value in my PHP array. If I've an array of all possible matches

$possible_matches = array(
  'heading-1'=> 'You can\'t do anything',
  'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
// what now?

And it changes the html like

<h1>You can't do anything</h1>
<p>Unless you show your code which you don't have so be ready for down votes</p>

How can I achieve this? Should I use regex?

webketje
  • 10,376
  • 3
  • 25
  • 54
  • please check this how create templates https://stackoverflow.com/questions/13071784/html-templates-php – Diego Avila May 02 '18 at 16:14
  • Did you really read the question or just assumed it through the title ? – Rameez Jawaid May 02 '18 at 16:19
  • Actually, @Tegito123 's suggestion is spot on. Don't parse HTML with regex (https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Nic3500 May 02 '18 at 16:25

1 Answers1

0

you can use foreach loop and str_replace like this

$html = '<h1>${heading-1}</h1>
<p>${paragraph}</p>';
$possible_matches = array(
  'heading-1'=> 'You can\'t do anything',
  'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
foreach($possible_matches as $key=> $value){
$html = str_replace('${'.$key.'}',$value,$html);
}
echo $html;

and if html template included in external file you can use file_get_contents to put the html in variable $html

Emad Elpurgy
  • 347
  • 1
  • 3
  • 8