php正則學(xué)了一些日子,抓了一些網(wǎng)站的數(shù)據(jù),從而發(fā)現(xiàn)每次都自己寫正則重新抓很麻煩,于是就想寫一個(gè)抓取特定標(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)容
下面隨便給出一個(gè)例子
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" >首頁(yè)/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" >相冊(cè)/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) "首頁(yè)" [1]=> string(6) "日志" [2]=> string(6) "LOFTER" [3]=> string(6) "相冊(cè)" [4]=> string(6) "博友" [5]=> string(9) "關(guān)于我" }
查看源碼可以看到
array(6) {
[0]=>
string(6) "首頁(yè)"
[1]=>
string(6) "日志"
[2]=>
string(6) "LOFTER"
[3]=>
string(6) "相冊(cè)"
[4]=>
string(6) "博友"
[5]=>
string(9) "關(guān)于我"
}
第一次寫blog好緊張哈哈哈,希望會(huì)對(duì)大家有用,也希望大家能指出代碼其中的問題,測(cè)試做的不是很多~~
以上所述是小編給大家介紹的PHP正則表達(dá)式抓取某個(gè)標(biāo)簽的特定屬性值的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
您可能感興趣的文章:- php使用正則表達(dá)式獲取字符串中的URL
- Ajax和PHP正則表達(dá)式驗(yàn)證表單及驗(yàn)證碼
- PHP利用正則表達(dá)式實(shí)現(xiàn)手機(jī)號(hào)碼中間4位用星號(hào)(*)替換顯示功能