向引擎添加条件语句

时间:2013-05-09 19:23:45

标签: php

我正在尝试添加使用条件语句到我正在尝试开发的这个基本引擎的能力,我无法弄清楚为什么它不起作用。有人可以帮忙吗?它不会取代文本。

这里是条件语句的template.php

<?php

class Template {
    private $vars = array();

    public function assign($key, $value) {
        $this->vars[$key] = $value;
    }

    public function render($file_name) {
        $path = $file_name . '.html';

        if (file_exists($path)) {

            $content = file_get_contents($path);

            foreach ($this->vars as $key => $value) {
                $content = preg_replace('/\{' . $key . '\}/', $value, $content);
            }

            $content = preg_replace('/\{if (.*)\}/', '<?php if ($1): ?>', $content);
            $content = preg_replace('/\{elseif (.*)\}/', '<?php elseif ($1): ?>', $content);
            $content = preg_replace('/\{else\}/', '<?php else: ?>', $content);
            $content = preg_replace('/\{\/if\}/', '<?php endif; ?>', $content);

            eval(' ?>' . $content . '<?php ');

        } else {
            exit('<h4>Engine error...</h4>');
        }
    }
}

?>

这是html中的实现

<div class="container">
            <div id="content">
                <h3>{pagetitle}</h3>
                <hr />
                <span>My name is {username} and I am {age} years old</span>

                {if ({age}==21)}
                    21
                {elseif ({age}==22)}
                    22
                {else}
                    none
                {/if}

           </div>
</div>

它在字面上打印出上面的条件块,因为你看到它是内联的

1 个答案:

答案 0 :(得分:1)

我猜你需要制作所有的正则表达式。

做这样的事情:

/\{if (.*)\}/

将替换{if的第一个实例与}的最后一个实例之间的所有内容。通过在模式中使用U标志来使比赛不成对:

/\{if (.*)\}/U