//你的.*用得太随意了,匹配任意字符的东西,用前要三思.
//任意抽取一部分正则式...
//'/(<!--top: (\d{5}).+<!--end: \2.*)/',这样的正则式肯定会匹配到的,因为<!--top: (\d{5}).+<!--end: \2首先匹配到了
//=====================
//<!--top: 66924-->
//<ul><!--insert: 66924-->
//</ul><!--end: 66924-->
//========================
//ok,这是你想要的.但是别忘了后面的.*,,在距离下一个匹配之前不是还有字符串吗,结果就有了你不想看到的局面.
[7] => <!--top: 66924-->
<ul><!--insert: 66924-->
</ul><!--end: 66924-->
</ul><!--end: 66922-->//[9]同理,会匹配到字符串结束位置,因为你的.*
//try....
    $str= file_get_contents("n1.txt");
        //$ptn='/(<!--top: (\d{5}).+<!--end: \2.*){5}/s' //该子模式要求匹配5次,本来这个文件不能匹配出来,因为这个文件最多能匹配4次,但结果却匹配成功了,为了检查到底匹配了哪五次,我把这个模式字符串展开成下面的样子来匹配
    $ptn='/(<!--top: (\d{5})(.+?)<!--end: \2-->)/s';
    if(preg_match_all($ptn, $str, $m))
        print_r(array_map('htmlspecialchars',$m[0]));//这样就可以打印m[0]m[1]m[2]m[3]到底是哪4个匹配了

解决方案 »

  1.   

    //<!--top: (\d{5}).+<!--end: \2首先匹配到了
    //=====================
    //<!--top: 66924-->
    //<ul><!--insert: 66924-->
    //</ul><!--end: 66924
    //========================
      

  2.   


    呵呵,非常感谢!其实我刚发出贴子两分钟,我就发现我问题出在哪里了。
    不过我还是想等个耐心的高手,因为我以前发的一个贴子,下面这个问题,到现在我也没找出原因:
    http://topic.csdn.net/u/20081202/11/5832d4d2-4511-4659-9ae1-04bedf1dca75.html如果你有时间,还希望多多指教。上面贴子如果你能帮我找出原因,我再加50分。
    谢啦,先结这个贴子。
      

  3.   

    <?php
    $str= file_get_contents("n1.txt");
    $ptn='/<!--top:[\s]*([\d]+)[\s]*-->(.*)<!--end:[\s]*\\1[\s]*-->/is';
    preg_match_all($ptn, $str, $m);
    print_r($m[1]);
    //[0] => 66963 [1] => 66931 [2] => 66926 [3] => 66916
    ?>
    这样其实还是不够的。
    相关帖子:http://forums.devnetwork.net/viewtopic.php?f=38&t=71791
    http://www.skdevelopment.com/php-regular-expressions.php