Replacing {{string}} within php file

php, replace, variables

Solution

You can use PHP as template engine. No need for `{{newsletter}}` constructs.

Say you output a variable `$newsletter` in your template file.

// templates/contact.php

<?= htmlspecialchars($newsletter, ENT_QUOTES); ?>

To replace the variables do the following:

$newsletter = 'Your content to replace';

ob_start();        
include('templates/contact.php');
$contactStr = ob_get_clean();

echo $contactStr;

// $newsletter should be replaces by `Your content to replace`

In this way you can build your own template engine.

class Template
{
    protected $_file;
    protected $_data = array();

    public function __construct($file = null)
    {
        $this->_file = $file;
    }

    public function set($key, $value)
    {
        $this->_data[$key] = $value;
        return $this;
    }

    public function render()
    {
        extract($this->_data);
        ob_start();
        include($this->_file);
        return ob_get_clean();
    }
}

// use it
$template = new Template('templates/contact.php');
$template->set('newsletter', 'Your content to replace');
echo $template->render();

The best thing about it: You can use conditional statements and loops (full PHP) in your template right away.

Use this for better readability: https://www.php.net/manual/en/control-structures.alternative-syntax.php

Problem

I'm including a file in one of my class methods, and in that file has html + php code. I return a string in that code. I explicitly wrote `{{newsletter}}` and then in my method I did the following: ``` $contactStr = include 'templates/contact.php'; $contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr); ``` However, it's not replacing the string. The only reason I'm doing this is because when I try to pass the variable to the included file it doesn't seem to recognize it. ``` $newsletterStr = 'some value'; $contactStr = include 'templates/contact.php'; ``` So, how do I implement the string replacement method?

Original source