drkwpgrdb092239314 2012-06-14 14:03
浏览 74
已采纳

用字符串变量替换preg_match中的引用

I'm trying to template a document, I want to replace section of the document with dynamic text by searching a document for [%text%] and replacing it with $array['text'] or $text. I know I can use str_replace("[%text%]", $array['text'], $page), but I want to find all instances of [%(.*?)%] and replace with with $array[$1] instead of $1. I've tried using create_function($matches, $array), but it complains about Missing argument 2 for {closure}().

$page = preg_replace('#\[%(.*?)%\]#is', $array["$1"], $page);
  • 写回答

3条回答 默认 最新

  • douyinglan2599 2012-06-14 14:19
    关注

    You can preg_match_all('#[%(.*?)%]#is', $page, $matches); and then

    if(count($matches == 2))
    {
      $key = 0;
      foreach(array_unique($matches[0]) as $val)
      {
        if(isset($array[$key]))
        {
          $page = str_replace($val, $array[$key++], $page);
        }
        else
        {
          break; // more matches than array elements
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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