Skip to content
PHP Logo

How can I create a replace function in PHP that can replace placeholders and execute PHP code within HTML templates?

To create a replace function in PHP that can replace placeholders and execute PHP code within HTML templates, you can use the `preg_replace_callback` function along with a custom callback function. This callback function can evaluate any PHP code within the placeholders and return the desired output. By using regular expressions to identify the placeholders in the HTML template, you can dynamically replace them with the evaluated PHP code.

php
function replacePlaceholders($html) {
    return preg_replace_callback('/{{(.*?)}}/', function($matches) {
        ob_start();
        eval("?>".$matches[1]);
        return ob_get_clean();
    }, $html);
}

// Example usage
$htmlTemplate = '<h1>Hello, {{echo "World";}}!</h1>';
echo replacePlaceholders($htmlTemplate);