Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm making a simple PHP Template system but I'm getting an error I cannot solve, the thing is the layout loads excellent but many times, can't figure how to solve, here my code

Class Template {

private $var = array();

public function assign($key, $value) {

    $this->vars[$key] = $value;

}

public function render($template_name) {

    $path = $template_name.'.tpl';
    if (file_exists($path)) {

        $content = file_get_contents($path);

        foreach($this->vars as $display) {


            $newcontent = str_replace(array_keys($this->vars, $display), $display, $content);
            echo $newcontent;

        }

    } else {

        exit('<h1>Load error</h1>');

    }
}

}

And the output is

Title is : Welcome to my template system

Credits to [credits]

Title is : [title]

Credits to Credits to Alvaritos

As you can see this is wrong, but don't know how to solve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're better off with strtr:

$content = file_get_contents($path);
$new = strtr($content, $this->vars);
print $new;

str_replace() does the replaces in the order the keys are defined. If you have variables like array('a' => 1, 'aa' => 2) and a string like aa, you will get 11 instead of 2. strtr() will order the keys by length before replacing (highest first), so that won't happen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...