WebjxCom提示:PHP正則表達式提取超鏈接及其標題. |
有這么一段HTML,比較不規(guī)則的,如果要提取其中的鏈接地址和鏈接名稱,怎么弄?
//HTML
$str = '<a id="top8" class="p14" target="_top">歌曲列表</a><br><a target="_blank" id="bp" class="p14">中文金曲榜</a><br><td nowrap="nowrap">• <a id="top19" href="qingyinyue.html?top19" class="p14" target="_top">輕音樂</a></td>';
利用正則表達式是最簡單的,其它的辦法,偶米去想。。。
$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pat, $str, $m);
輸出方法:
print_r($m[2]);
print_r($m[4]);
或者:
for($i=0;$i<count($m[2]) ;$i++ ){
echo '<li><a href="'.$_SERVER['PHP_SELF'].'?url='.$m[2][$i].'">'.$m[4][$i].'</a>';
}
顯示結(jié)果是:
Array ( [0] => http://list.mp3.baidu.com/song/A.htm?top8 [1] => http://list.mp3.baidu.com/list/bangping.html [2] => qingyinyue.html?top19 ) Array ( [0] => 歌曲列表 [1] => 中文金曲榜 [2] => 輕音樂 )
于是,我們要采集某個網(wǎng)站的標題及鏈接地址方法就出來了。。。自己套用吧。。。