Search code examples
phphtmlpreg-replacepreg-replace-callback

rendering template to real html using preg_replace


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.


Solution

  • 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]}"'; 
       }
    }