简体   繁体   中英

Replacing {{string}} within php file

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?

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

This is a code i'm using for templating, should do the trick

  if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
      foreach ($m[1] as $i => $varname) {
        $template = str_replace($m[0][$i], sprintf('%s', $varname), $template);
      }
    }

maybe a bit late, but I was looking something like this.

The problem is that include does not return the file content, and easier solution could be to use file_get_contents function.

$template = file_get_contents('test.html', FILE_USE_INCLUDE_PATH);

$page = str_replace("{{nombre}}","Alvaro",$template);

echo $page;

based on @da-hype

<?php
$template = "hello {{name}} world! {{abc}}\n";
$data = ['name' => 'php', 'abc' => 'asodhausdhasudh'];

if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
    foreach ($m[1] as $i => $varname) {
        $template = str_replace($m[0][$i], sprintf('%s', $data[$varname]), $template);
    }
}


echo $template;
?>

Use output_buffers together with PHP-variables. It's far more secure, compatible and reusable.

function template($file, $vars=array()) {
    if(file_exists($file)){
        // Make variables from the array easily accessible in the view
        extract($vars);
        // Start collecting output in a buffer
        ob_start();
        require($file);
        // Get the contents of the buffer
        $applied_template = ob_get_contents();
        // Flush the buffer
        ob_end_clean();
        return $applied_template;
    }
}

$final_newsletter = template('letter.php', array('newsletter'=>'The letter...'));
<?php
//First, define in the template/body the same field names coming from your data source:
$body = "{{greeting}}, {{name}}! Are You {{age}} years old?";

//So fetch the data at the source (here we will create some data to simulate a data source)
$data_source['name'] = 'Philip';
$data_source['age'] = 35;
$data_source['greeting'] = 'hello';

//Replace with field name
foreach ($data_source as $field => $value) {
    //$body = str_replace("{{" . $field . "}}", $value, $body);
    $body = str_replace("{{{$field}}}", $value, $body);
}

echo $body; //hello, Philip! Are You 35 years old?

Note - An alternative way to do the substitution is to use the commented syntax.

But why does using the three square brackets work?

By default the square brackets allow you to insert a variable inside a string.

As in:

$name = 'James';
echo "His name is {$name}";

So when you use three square brackets around your variable, the innermost square bracket is dedicated to the interpolation of the variables, to display their values:

This {{{$field}}} turns into this {{field}}

Finally the replacement with str_replace function works for two square brackets.

no, don't include for this. include is executing php code. and it's return value is the value the included file returns - or if there is no return: 1.

What you want is file_get_contents() :

// Here it is safe to use eval(), but it IS NOT a good practice.
$contactStr = file_get_contents('templates/contact.php');
eval(str_replace("{{newsletter}}", $newsletterStr, $contactStr));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM