duanhuai7532 2015-01-21 22:54
浏览 58
已采纳

正则表达式PHP preg_match_all

I got this code from the WWW:

  private function initialize_loops($template){
        preg_match_all('/{LOOP:([w]+)[^}]*}((s*?.*?)*){\/LOOP:\1}/', $template, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $template = str_ireplace($match[0], '<!–LOOP('.$match[1].')–>', $template);
            $this->loop_templates[strtoupper($match[1])] = $match[2];
            if(!array_key_exists(strtoupper($match[1]), $this->loops)){
                $this->loops[strtoupper($match[1])] = array();
            }
        }
        return $template;
   }

The Input String is: (for example)

<tbody>
    {LOOP:USERLIST}
    <tr>
      <td>{VAR:ID}</td>
      <td>{VAR:D-NAME}</td>
      <td>{VAR:ROLE}</td>
      <td>{VAR:ACTIONS}</td>
    </tr>
    {/LOOP:USERLIST}
  </tbody>

I don't know for what reasons they created that RegEx in the code, becouse ist not working!

I Tried to get it workin on ReExr.com, so far I have:

/{LOOP:([^}]+)}((s*?.*?)*){\/LOOP:\1}/img

Thats still not working {LOOP:([^}]+)}{\/LOOP:\1} already works for {LOOP:USERLIST}{/LOOP:USERLIST}.

So my Problem is the middle Part: ((s*?.*?)*)

I absoluty cann't see why where is a s in the Expression or how it should work. Hope somebody has a Suggestion how to do it? Or an Explanation of ((s*?.*?)*)?

  • 写回答

2条回答 默认 最新

  • duanpin2009 2015-01-21 23:08
    关注

    Probably there's simply a backslash missing:

    ((\s*?.*?)*)
    

    At a first glance, it seems that they wanted to parse leading whitespaces separately. However, that doesn't explain why the spaces are in the same pattern group as the rest.

    Another possibility is that they noticed that . doesn't match newlines. But instead of using the proper pattern modifier "s" (PCRE_DOTALL), they tried to catch the newlines via the \s whitespace pattern.

    Either way, just ignore that crap. The following regex should do the trick:

    '/{LOOP:([^}]+)}(.*?){\/LOOP:\1}/sg'
    

    By the way, I don't see why you added the "i". Please don't do that. I don't think it is a good design for a template system to match {LoOp:test}...{/loOP:test}.

    Also, it doesn't make any sense to add the "m" modifier, since the regex doesn't contain any anchor, neither ^ nor $.

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

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动