php匹配指定div内容,在用php编写采集程序的时候,抓取到的网页数据有时候我们只需要一小段标签内容,怎么才能冲html代码中提取出来呢,这里提供一个函数示例,实现php匹配任意html标签内的所有内容:

/***匹配任意id的html标签内容**/functiongetWebTag($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);}elseif(stripos($data,'gb2312',$charset_pos)){$data=iconv('gb2312','utf-8',$data);}elseif(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)returnfalse;//未命中$divs=array();//合并所有divforeach($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){//<div$hit<div+1时div被命中if(($pre_matches[0][$index][1]<$hit)&&($hit<$pre_matches[0][$index+1][1])){$deeper=0;//弹出被命中div前的divwhile(array_shift($sort)!=$pre_matches[0][$index][1]&&($count--))continue;//对剩余div进行匹配,若下一个为前缀,则向下一层,$deeper加1,//否则后退一层,$deeper减1,$deeper为0则命中匹配,计算div长度foreach($sortas$key){if($divs[$key]=='p')$deeper++;elseif($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);