php正则匹配html中带class的div并选取其中内容的方法

yipeiwu_com7年前PHP代码库

本文实例讲述了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款本站的正则表达式在线工具供大家参考使用(包括正则生成、匹配与验证等功能):

JavaScript正则表达式在线测试工具:http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:http://tools.jb51.net/regex/create_reg

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP array_multisort()函数的使用札记

函数  bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC [, mixed $arg = SORT_REGULAR...

php调用云片网接口发送短信的实现方法

php调用云片网接口发送短信的实现方法 云片网发送短信 /** * [SendSms description] * @param [string] $tpl_conten...

PHP简单实现文本计数器的方法

本文实例讲述了PHP简单实现文本计数器的方法。分享给大家供大家参考,具体如下: <?php if (file_exists('count_file.txt'))...

php使用curl打开https网站的方法

本文实例讲述了php使用curl打开https网站的方法。分享给大家供大家参考。具体实现方法如下: $url = 'https://www.google.com.hk'; $ch...

PHP下利用shell后台运行PHP脚本,并获取该脚本的Process ID的代码

复制代码 代码如下:$command = '/usr/bin/php /pub/www/u111/job/Crondo/auto_collector.php &'; $process =...