php - replace string in template file

I do have that code:

ob_start();
include($this->testTpl);
$html = ob_get_clean();
$pattern = '/{{{\s*(.+?)\s*}}}(\r?\n)?/s';
echo preg_replace_callback($pattern, function($matches) {
    return "<?php htmlspecialchars({$matches[1]}); ?>";
}, $html);

and the testTpl file is a php file having this inside:

<div class="something">
<ul>
    <li>{{{ $data->something }}}</li>
</ul>

the text is replaced but when I echo it what's returned is:

<li><!--?php htmlspecialchars($data--->something); ?&gt;</li>

I don't have the smallest clue why that's happening... anyone any thoughts? any help is appreciated

Answer

Solution:

It's already PHP no need for another set of tags <?php ?>

ob_start();
include($this->testTpl);
$html = ob_get_clean();
$pattern = '/{{{\s*(.+?)\s*}}}(\r?\n)?/s';
echo preg_replace_callback($pattern, function($matches) {
    return htmlspecialchars({$matches[1]});
}, $html);

Answer

Solution:

I ended by doing that:

$html = file_get_contents($this->testTpl);
$pattern = '/{{{\s*(.+?)\s*}}}(\r?\n)?/s';
$output = preg_replace_callback($pattern, function($matches) {
    return "<?php echo htmlspecialchars($matches[1]); ?>";
}, $html);
file_put_contents(sys_get_temp_dir().'/temp.php', $output);
include(sys_get_temp_dir().'/temp.php');

in this way, the newly created file will be rendered correctly. If anyone has any other idea how to do it without writing the file physically on the /tmp folder...

Source