duanchi0897 2013-06-11 22:17
浏览 136
已采纳

PHP Preg_replace占位符

Hi I'm writing something for handling my views an I need a preg_replace here, but i can't seem to get it working so I've scrapped the code.

the strings I am trying to replace are dynamic based on a template, e.g.

{{name}} is {{age}} years old

And the passed information into the function is an array e.g.

array( 'name' => 'John Doe', 'age' => '27' );

The pattern I have so far is \{{([a-zA-Z0-9]+)\}} however this only seems to match one pair of braces.

I'm also having a problem looping through results in preg_match_all..

Thanks in advance

  • 写回答

3条回答 默认 最新

  • doucigua0449 2013-06-11 22:23
    关注

    preg_replace_callback seems like a good candidate.

    $str = "{{name}} is {{age}} years old";
    $values = array( 'name' => 'John Doe', 'age' => '27' );
    echo preg_replace_callback("/\{{([a-z0-9]+?)\}}/i", function ($result)
    use ($values) {
       if (isset($result[1])) {
          return $values[$result[1]];
       }
    }, $str);
    

    The main issue is that {{[a-z]+}} will match from {{name ... age}}. Using the ? makes the + reluctant so it only matches up to the first } rather than the last.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写