dongpankao6133 2013-05-10 22:57
浏览 42
已采纳

为什么preg替换不接受数组

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

  • 写回答

1条回答 默认 最新

  • drevls8138 2013-05-10 23:37
    关注

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

    $names = 'array(
            "Name",
            "Name2",
            "Name3",
            "Name4"
        )';
    
    $gate->assign('members', $names);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题