PHP正則表達(dá)式抓取某個標(biāo)簽的特定屬性值的方法
php正則學(xué)了一些日子,抓了一些網(wǎng)站的數(shù)據(jù),從而發(fā)現(xiàn)每次都自己寫正則重新抓很麻煩,于是就想寫一個抓取特定標(biāo)簽具有特定屬性值的接口通用,直接上代碼。
//$html-被查找的字符串 $tag-被查找的標(biāo)簽 $attr-被查找的屬性名 $value-被查找的屬性值
function get_tag_data($html,$tag,$attr,$value){
$regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
echo $regex."<br>";
preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
return $matches[1];
}
//返回值為數(shù)組 查找到的標(biāo)簽內(nèi)的內(nèi)容
下面隨便給出一個例子
header("Content-type: text/html; charset=utf-8");
$temp = '<ul class="noul clearfix">
<li class="w w0">
<a class="i i0 fc01 h" hidefocus="true" >首頁</a>
</li>
<li class="w w1 selected">
<a class="i i1 fc01 h" hidefocus="true" >日志</a>
</li>
<li class="w w9">
<a class="i i9 fc01 h" hidefocus="true" >LOFTER</a>
</li>
<li class="w w2">
<a class="i i2 fc01 h" hidefocus="true" >相冊</a>
</li>
<li class="w w5">
<a class="i i5 fc01 h" hidefocus="true" >博友</a>
</li>
<li class="w w6">
<a class="i i6 fc01 h" hidefocus="true" >關(guān)于我</a>
</li>
</ul>';
$result = get_tag_data($temp,"a","class","fc01");
var_dump($result);
輸出結(jié)果為
array(6) { [0]=> string(6) "首頁" [1]=> string(6) "日志" [2]=> string(6) "LOFTER" [3]=> string(6) "相冊" [4]=> string(6) "博友" [5]=> string(9) "關(guān)于我" }
查看源碼可以看到
array(6) {
[0]=>
string(6) "首頁"
[1]=>
string(6) "日志"
[2]=>
string(6) "LOFTER"
[3]=>
string(6) "相冊"
[4]=>
string(6) "博友"
[5]=>
string(9) "關(guān)于我"
}
第一次寫blog好緊張哈哈哈,希望會對大家有用,也希望大家能指出代碼其中的問題,測試做的不是很多~~
以上所述是小編給大家介紹的PHP正則表達(dá)式抓取某個標(biāo)簽的特定屬性值的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Android 2018最新手機(jī)號驗(yàn)證正則表達(dá)式方法
這篇文章主要介紹了Android 2018最新手機(jī)號驗(yàn)證正則表達(dá)式方法,需要的朋友可以參考下2018-03-03
javascript將字符串中的多個空格替換為一個空格的正則實(shí)例
這篇文章主要介紹了javascript將字符串中的多個空格替換為一個空格的正則實(shí)例,需要的朋友可以參考下2016-12-12
用Java正則去掉字符串中重復(fù)出現(xiàn)的字符
abcde 順序可以不一樣,也就是去掉重復(fù)出現(xiàn)的字符2010-12-12

