-1

I want to replace template with HTML code, and it worked good, but the problem is that I use a php code inside the rendered HTML, and it can't run just printed like a string. this is the code:

$template = '[text required id="first_name" label="First Name"]';

$pattern = ['/^\[([a-z]+)\s{1,}(required)?\s{1,}(?:id|label)="([^"]+)"\s{1,}(?:id|label)="([^"]+)"\s{0,}\]/im'];

$replacement = ['<label for="$3">$4 ($2)</label>
<input type="text" name="$3" id="$3" 
<?php if( !empty($data["$3"]) ) { echo \'value="{$data[\"$3\"]}"\'; }?> />'];

$output = preg_replace($pattern, $replacement, $template);

echo $output;

And this is the output:

enter image description here

and this is the source of the output:

enter image description here

Thank you in advance.

Mohamed Kamel
  • 93
  • 1
  • 13

2 Answers2

0

As you want to evaluate PHP so it has to be on server side and will be executed before it is output from the server. I hope you are clear on that.

Now, as you need to run it on the server and you are producing the code itself on the server how about running it directly without storing it in a string, unless you are getting the php code from somewhere else as a string like from database.

However, you can use eval function to evaluate a string of code in PHP. But, I would not recommend it is a security risk for your website.

As PHP manual says:

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

So you should be very careful with this.

Hope it would help.

Parantap Parashar
  • 1,930
  • 1
  • 14
  • 22
0

This is the answer

<?php

$template = '[text required id="first_name" label="First Name"]';



$pattern = ['/^\[([a-z]+)\s{1,}(required)?\s{1,}(?:id|label)="([^"]+)"\s{1,}(?:id|label)="([^"]+)"\s{0,}\]/im'];

$replacement = ['<label for="$3">$4 ($2)</label>
<input type="text" name="$3" id="$3" '. get_data("$3") .' />'];


$output = preg_replace($pattern, $replacement, $template);


echo $output;


function get_data($index){
   if( !empty($data[$index]) ) { 
      echo 'value="{$data[$index]}"'; 
   }
}
Mohamed Kamel
  • 93
  • 1
  • 13