为什么preg替换不接受数组

时间:2013-05-10 22:57:52

标签: php

我正在尝试使用preg_replace添加foreach语句,但它不断抛出错误preg_replace(): Parameter mismatch, pattern is a string while replacement is an array由于处理foreach的{​​{1}}它不允许我放置阵列。我怎样才能同时使用它们?

这里是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 ');

这是HTML

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

我只需要知道如何修复错误,我认为该错误涉及使{foreach ({members} as $member)} <p>$member</p> {/foreach} 函数接受数组

1 个答案:

答案 0 :(得分:1)

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

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

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