php匹配指定标签所有内容,php匹配指定标签的内容

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(‘/

preg_match_all(‘/

$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){

//

if(($pre_matches[0][$index][1] 

$deeper = 0;

//弹出被命中div前的div

while(array_shift($sort) != $pre_matches[0][$index][1] && ($count--)) continue;

//对剩余div进行匹配,若下一个为前缀,则向下一层,$deeper加1,

//否则后退一层,$deeper减1,$deeper为0则命中匹配,计算div长度

foreach($sort as $key){

if($divs[$key] == ‘p‘) $deeper++;

else if($deeper == 0) {

$length = $key-$pre_matches[0][$index][1];

break;

}else {

$deeper--;

}

}

$hitDivString = substr($data,$pre_matches[0][$index][1],$length).‘‘.$tag.‘>‘;

break;

}

}

return $hitDivString;

}

调用示例

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

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

原文:http://taoyouth.blog.51cto.com/2793776/1661859

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值