1

我正在尝试添加 foreach 语句,preg_replace但它一直抛出错误preg_replace(): Parameter mismatch, pattern is a string while replacement is an array,因为foreach它处理vars它不允许我放置数组。我怎样才能让它同时使用?

这里有class

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);
        }

        /* PHP Tags */
        $content = preg_replace('/\{php\}/', '<?php ', $content);
        $content = preg_replace('/\{\/php\}/', ' ?>', $content);

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

        /* FOREACH Statement */
        $content = preg_replace('/\{foreach (.*)\}/e', '<?php foreach ($1) { ?>', $content);
        $content = preg_replace('/\{\/foreach\}/e', '<?php }; ?>', $content);

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

这是变量文件

include_once 'gate.php';

$gate = new Gate;

$gate->assign('pagetitle', 'Test Document');
$gate->assign('username', 'Zach');
$gate->assign('age', 21);

$names = array(
        "Name",
        "Name2",
        "Name3",
        "Name4"
    );

$gate->assign('members', $names);

$gate->render('test');

这是HTML

{foreach ({members} as $member)}
       <p>$member</p>
{/foreach}

我只需要知道如何修复我认为涉及使数组被preg_replace函数接受的错误

4

1 回答 1

1

设置$names为包含 PHP 代码的字符串以创建文字数组:

$names = 'array(
        "Name",
        "Name2",
        "Name3",
        "Name4"
    )';

$gate->assign('members', $names);
于 2013-05-10T23:37:29.010 回答