php正則匹配html中帶class的div並選取其中內容的方法_php技巧

來源:互聯網
上載者:User

本文執行個體講述了php正則匹配html中帶class的div並選取其中內容的方法。分享給大家供大家參考。具體分析如下:

先看一段html代碼:

複製代碼 代碼如下:
<div class="chartInfo"> 
 <div class="line"></div>
 <div class="tideTable"> 
     <strong>潮汐表</strong>資料僅供參考
     <table width="500" border="0" cellspacing="0" cellpadding="0">
       <tbody><tr> 
  <td width="100"><p><span>潮時 (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>時區:-1000 (東10區)  潮高基準面:在平均海平面下174CM</h2> 
       </div> 
 <div class="chart"> 
 </div> 
</div>

這是來源程式裡邊的一部分,為了容易看懂,刪減了一大部分,只取<div class="tideTable"> div塊中的內容

首頁先用file_get_content或curl擷取內容部分,我用的是curl。

複製代碼 代碼如下:
$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的看代碼,列印看一下效果。

PS:關於正則,這裡再為大家提供2款本站的Regex線上工具供大家參考使用(包括正則產生、匹配與驗證等功能):

JavaScriptRegex線上測試載入器:http://tools.jb51.net/regex/javascript

Regex線上產生工具:http://tools.jb51.net/regex/create_reg

希望本文所述對大家的php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.