日期:2014-05-17  浏览次数:20533 次

正则匹配嵌套div ,求PHP实现~
如下html串:
$str = '<div class="am1">
    <div class="image">1111111111</div>
    <div class="image">2222222222</div>
    <a href="test.php">link1</a>
 </div>
 <div class="am1">
     <div class="image">1111111111</div>
     <img src="./tt.gif" />
     <div class="image">2222222222</div>
 </div>';
需要匹配出的结果:
    将<div class="am1">中的内容匹配出来, 即:
   1=>     
           <div class="image">1111111111</div>
           <div class="image">2222222222</div>
           <a href="test.php">link1</a>

   2=>     
           <div class="image">1111111111</div>
           <img src="./tt.gif" />
           <div class="image">2222222222</div>
php程序实现,在线等~
        
------解决方案--------------------
引用:
$patten='/(<div class="am1">(*)</div>)/';
preg_match_all($patten,$str,$match);


没有这么简单.因为会有多个</div>,你应该从内层开始查找,然后一层一层的往外,知道匹配到<div class="am1"></div>为止
------解决方案--------------------
<?php
$str = '<div class="am1">
    <div class="image">1111111111</div>
    <div class="image">2222222222</div>
    <a href="test.php">link1</a>
</div>
<div class="am1">
     <div class="image">1111111111</div>
     <img src="./tt.gif" />
     <div class="image">2222222222</div>
</div>';
if (preg_match_all('#<div[^>]*>((?>[^</div>]+
------解决方案--------------------
<a.+?>.+?</a>
------解决方案--------------------
<img.+?/>
------解决方案--------------------
(?R))*)</div>#is', $str, $matches)){
print_r($matches);
}
 ?>