PHP正则实战之匹配嵌套标签

内容:

其他文本其他文本 <div>仅单层 </div> </div>(注意:后面多一个 </div>)
其他文本其他文本其他文本
<div>外层
     <div>中层
         <div>内层 </div>
     </div>
</div>
# 这是另一种情况 
# start 闭合错误
<div>外层
     <div>中层
         <div>内层 </div>
     </div>
</font> 
# end 闭合错误
其他文本 <font>外层 <span>里层 </span> </font>其他文本其他文本……

PHP代码:

$p = "/<(&#91;a-z&#93;+)&#91;^>]*>([^<>]|(?R))*<\/\\1>/is";
preg_match_all($p,$str,$m);
print_r($m[0]);

结果:

Array
(
    [0] => <div>仅单层 </div>
    [1] => <div>外层
     <div>中层
         <div>内层 </div>
     </div>
</div>
    [2] => <div>中层
         <div>内层 </div>
     </div>
    [3] => <font>外层 <span>里层 </span> </font>
)

PHP正则实战之匹配图片地址

内容:

<a href="/item/2864756" target="_blank"><img src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg" height="268" width="200px"/></a>
<a href="/item/2864756" target="_blank"><img src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg" height="268" width="200px"/></a>
<a href="/item/2864756" target="_blank"><img src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg" height="268" width="200px"/></a>
<a href="/item/2864756" target="_blank"><img src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg" height="268" width="200px"/></a>
<a href="/item/2864756" target="_blank"><img src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg" height="268" width="200px"/></a>

PHP代码:

$p = "/src=\"([^\"]+)/isu";
//$p = "/<&#91;^>]+>/isu";
//$p = "/<a&#91;^>]+>/isu";
preg_match_all($p, $html, $m);
var_dump($m);

结果:

Array
(
    [0] => Array
        (
            [0] => src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [1] => src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [2] => src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [3] => src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [4] => src="http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
        )

    [1] => Array
        (
            [0] => http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [1] => http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [2] => http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [3] => http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
            [4] => http://imgtest-lx.meilishuo.net/pic/r/e6/14/28b4766b65373ae6a3b3faccc81f_400_536.jpg
        )

)