php如何獲取標籤的值

2020-07-16 10:06:47

PHP使用正規表示式獲取指定標籤的值:

//$html-被查詢的字串 $tag-被查詢的標籤 $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];
}
//返回值為陣列 查詢到的標籤內的內容

範例

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" href="http://phpway.blog.163.com/">首頁</a>
</li>
<li class="w w1 selected">
<a class="i i1 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/blog/">紀錄檔</a>
</li>
<li class="w w9">
<a class="i i9 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/loftarchive/">LOFTER</a>
</li>
<li class="w w2">
<a class="i i2 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/album/">相簿</a>
</li>
<li class="w w5">
<a class="i i5 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/friends/">博友</a>
</li>
<li class="w w6">
<a class="i i6 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/profile/">關於我</a>
</li>
</ul>';
$result = get_tag_data($temp,"a","class","fc01");
var_dump($result);

輸出:

array(6) { [0]=> string(6) "首頁" [1]=> string(6) "紀錄檔" [2]=> string(6) "LOFTER" [3]=> string(6) "相簿" [4]=> string(6) "博友" [5]=> string(9) "關於我" }
以上就是php如何獲取標籤的值的詳細內容,更多請關注TW511.COM其它相關文章!