您现在的位置是:首页 > PHP学习

李清波 2021-07-31 PHP学习 1175 复制当前网址

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


参考代码:

<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。


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的看代码,打印看一下效果。

文章来源:https://www.liqingbo.com/blog-1770.html

评论