Zach Starnes
Zach Starnes

Reputation: 3198

Why is preg replace not accepting array

I am trying to add foreach statements with preg_replace but it keeps throwing the error preg_replace(): Parameter mismatch, pattern is a string while replacement is an array Because of the foreach that deals with the vars it wont allow me to place arrays. How can I make it use both?

here are the 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 ');

here is the variable file

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

and here is the HTML

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

I just need to know how to fix the error which i assume involves making the array become accepted by the preg_replace function

Upvotes: 1

Views: 1134

Answers (1)

Barmar
Barmar

Reputation: 782004

Set $names to a string containing the PHP code to create a literal array:

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

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

Upvotes: 1

Related Questions