php匹配指定標籤的內容

來源:互聯網
上載者:User
php匹配指定div內容,在用php編寫採集程式的時候,抓取到的網頁資料有時候我們只需要一小段標籤內容,怎麼才能沖html代碼中提取出來呢,這裡提供一個函數樣本,實現php匹配任意html標籤內的所有內容:

/*** 匹配任意id的html標籤內容* */function getWebTag($tag_id,$tag='div',$data=false){             $charset_pos = stripos($data,'charset');        if($charset_pos) {            if(stripos($data,'utf-8',$charset_pos)) {                $data = iconv('utf-8','utf-8',$data);            }else if(stripos($data,'gb2312',$charset_pos)) {                $data = iconv('gb2312','utf-8',$data);            }else if(stripos($data,'gbk',$charset_pos)) {                $data = iconv('gbk','utf-8',$data);            }        }               preg_match_all('/<'.$tag.'/i',$data,$pre_matches,PREG_OFFSET_CAPTURE);    //擷取所有div首碼        preg_match_all('/<\/'.$tag.'/i',$data,$suf_matches,PREG_OFFSET_CAPTURE); //擷取所有div尾碼        $hit = strpos($data,$tag_id);        if($hit == -1) return false;    //未命中        $divs = array();    //合并所有div        foreach($pre_matches[0] as $index=>$pre_div){            $divs[(int)$pre_div[1]] = 'p';            $divs[(int)$suf_matches[0][$index][1]] = 's';           }               //對div進行排序        $sort = array_keys($divs);        asort($sort);               $count = count($pre_matches[0]);        foreach($pre_matches[0] as $index=>$pre_div){            //';                break;            }        }        return $hitDivString;}

調用樣本

$html=file_get_contents('http://www.baidu.com');

$divContent=getWebTag('id="content"','div',$html);

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.