php正則匹配html中帶class的div并選取其中內(nèi)容的方法
參考代碼:
<div class="chartInfo"><div class="line"></div><div class="tideTable"><strong>潮汐表</strong>數(shù)據(jù)僅供參考<table width="500" border="0" cellspacing="0" cellpadding="0"><tbody><tr><td width="100"><p><span>潮時(shí) (Hrs)</span></p></td><td width="100"><p>00:58</p></td><td width="100"><p>05:20</p></td><td width="100"><p>13:28</p></td><td width="100"><p>21:15</p></td></tr><tr><td><p><span>潮高 (cm)</span></p></td><td width="100"><p>161</p></td><td width="100"><p>75</p></td><td width="100"><p>288</p></td><td width="100"><p>127</p></td></tr></tbody></table><h2>時(shí)區(qū):-1000 (東10區(qū)) 潮高基準(zhǔn)面:在平均海平面下174CM</h2></div><div class="chart"></div></div>
這是源程序里邊的一部分,為了容易看懂,刪減了一大部分,只取<div class="tideTable"> div塊中的內(nèi)容
首頁先用file_get_content或curl獲取內(nèi)容部分,我用的是curl。
php代碼
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt( $ch, CURLOPT_HEADER, 0 );curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );$return = curl_exec( $ch );curl_close( $ch );$regex4="/<div class=\"tideTable\".*?>.*?<\/div>/ism";if(preg_match_all($regex4, $return, $matches)){print_r($matches);}else{echo '0';}
這樣就可以了,不多解釋,懂PHP的看代碼,打印看一下效果。
評(píng)論
圖片
表情
